Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Offer an opt-in PgBouncer beside PostgreSQL

Juan Denis45f7100d931f
diff --git a/backend/app/api/app_attachments.py b/backend/app/api/app_attachments.py
index 3738158c..c2b6f1f7 100644
--- a/backend/app/api/app_attachments.py
+++ b/backend/app/api/app_attachments.py
@@ -88,3 +88,34 @@ def detach(app_id, attachment_id):
if warning:
body['warning'] = warning
return jsonify(body)
+
+
+# ==================== CONNECTION POOLING (plan 86 §D1) ====================
+
+@app_attachments_bp.route('/<int:app_id>/pooler', methods=['GET'])
+@viewer_required
+def get_pooler(app_id):
+ from app.services import pooler_service
+ app = AppAttachmentService.live_app(app_id)
+ if app is None or not ResourceGrantService.can_access_app(get_current_user(), app):
+ raise NotFoundError('Application not found')
+ return jsonify({'available': pooler_service.is_postgres_engine(app),
+ 'enabled': bool(app.pooler_enabled),
+ 'host': pooler_service.container_name(app),
+ 'tradeoff': pooler_service.TRADEOFF})
+
+
+@app_attachments_bp.route('/<int:app_id>/pooler', methods=['PUT'])
+@developer_required
+def set_pooler(app_id):
+ from app.services import pooler_service
+ app = AppAttachmentService.live_app(app_id)
+ if app is None or not ResourceGrantService.can_edit_app(get_current_user(), app):
+ raise NotFoundError('Application not found')
+ if not pooler_service.is_postgres_engine(app):
+ raise ValidationError('Connection pooling is for an installed PostgreSQL')
+ data = request.get_json(silent=True) or {}
+ if not isinstance(data.get('enabled'), bool):
+ raise ValidationError("'enabled' must be true or false")
+ result = pooler_service.set_enabled(app, data['enabled'])
+ return jsonify(result)
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index 743f9ae3..a22fbc8d 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -114,6 +114,8 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model):
# Page-cache TTL in seconds (plan 86 §B3). NULL = the 10s default; the
# renderer clamps to NginxService.MICROCACHE_TTL_MAX.
micro_cache_ttl = db.Column(db.Integer, nullable=True)
+ # Opt-in PgBouncer sidecar for a PostgreSQL engine app (plan 86 §D1).
+ pooler_enabled = db.Column(db.Boolean, nullable=True)
# Environment linking
environment_type = db.Column(db.String(20), default='standalone') # 'production', 'development', 'staging', 'standalone'
@@ -233,6 +235,7 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model):
'private_url_enabled': self.private_url_enabled,
'micro_cache_enabled': bool(self.micro_cache_enabled),
'micro_cache_ttl': self.micro_cache_ttl,
+ 'pooler_enabled': bool(self.pooler_enabled),
'environment_type': self.environment_type,
'linked_app_id': self.linked_app_id,
'shared_config': self._json_read('shared_config', None),
diff --git a/backend/app/services/compose_env_service.py b/backend/app/services/compose_env_service.py
index 12b146be..e4d85d7f 100644
--- a/backend/app/services/compose_env_service.py
+++ b/backend/app/services/compose_env_service.py
@@ -204,6 +204,16 @@ class ComposeEnvService:
services_block.setdefault(name, {})['networks'] = {
'default': {}, SHARED_NETWORK: {}}
+ # Opt-in PgBouncer beside a PostgreSQL engine (plan 86 §D1): a whole
+ # extra service, reachable from apps over the shared network only.
+ from app.services import pooler_service
+ pooler = pooler_service.sidecar(app, services)
+ if pooler:
+ pooler['networks'] = {'default': {}, SHARED_NETWORK: {}}
+ pooler['environment'] = {k: cls._escape(v) for k, v in pooler['environment'].items()}
+ services_block[pooler_service.POOLER_SERVICE] = pooler
+ joined = joined or [pooler_service.POOLER_SERVICE]
+
if not services_block:
# Nothing to inject → no override should exist.
return {'applies': True, 'path': override_path, 'content': None}
diff --git a/backend/app/services/pooler_service.py b/backend/app/services/pooler_service.py
new file mode 100644
index 00000000..7cda6252
--- /dev/null
+++ b/backend/app/services/pooler_service.py
@@ -0,0 +1,89 @@
+"""Opt-in PgBouncer beside an installed PostgreSQL (plan 86 §D1).
+
+Turning pooling on adds a ``pgbouncer`` service to the PostgreSQL app's
+managed compose override: same project, container ``<app>-pooler``, on the
+shared service network, no host port. Apps then choose per connection:
+``fromService: <pg>.connectionString`` stays direct, and ``pooledUrl`` /
+``pooledConnectionString`` go through the pooler.
+
+Transaction pooling is the mode: many app connections share few server
+connections. It breaks session state: session-level prepared statements in
+some drivers, ``LISTEN``/``NOTIFY``, advisory locks and ``SET`` without
+``LOCAL``. So nothing switches to the pooled URL on its own, and the UI says
+so where the choice is made.
+"""
+from typing import Dict, Optional
+
+POOLER_IMAGE = 'edoburu/pgbouncer:v1.24.1-p1'
+POOLER_SERVICE = 'pgbouncer'
+POOL_MODE = 'transaction'
+MAX_CLIENT_CONN = 500
+DEFAULT_POOL_SIZE = 20
+
+TRADEOFF = ('Transaction pooling breaks session features: prepared statements in some '
+ 'drivers, LISTEN/NOTIFY, advisory locks and session SET. Apps keep the '
+ 'direct connection unless they switch to the pooled URL.')
+
+
+def container_name(app) -> str:
+ return f'{app.name}-pooler'
+
+
+def is_postgres_engine(app) -> bool:
+ from app.services.service_connection_service import _template_for
+ from app.services.template_service import TemplateService
+ engine = TemplateService.engine_metadata(_template_for(app) or {}) or {}
+ return engine.get('protocol') == 'postgresql'
+
+
+def sidecar(app, base_services: Dict) -> Optional[Dict]:
+ """The compose service to add to ``app``'s override, or None."""
+ if not getattr(app, 'pooler_enabled', False) or not base_services:
+ return None
+ if not is_postgres_engine(app):
+ return None
+ from app.services.service_connection_service import _install_variables, _template_for
+ from app.services.template_service import TemplateService
+ engine = TemplateService.engine_metadata(_template_for(app) or {}) or {}
+ variables = _install_variables(app)
+ password = variables.get(engine.get('admin_password_var') or '', '')
+ if not password:
+ return None
+ primary = next(iter(base_services))
+ return {
+ 'image': POOLER_IMAGE,
+ 'container_name': container_name(app),
+ 'restart': 'unless-stopped',
+ 'depends_on': [primary],
+ 'environment': {
+ 'DB_HOST': primary,
+ 'DB_PORT': '5432',
+ 'DB_USER': engine.get('admin_user') or 'postgres',
+ 'DB_PASSWORD': password,
+ 'POOL_MODE': POOL_MODE,
+ 'AUTH_TYPE': 'scram-sha-256',
+ 'MAX_CLIENT_CONN': str(MAX_CLIENT_CONN),
+ 'DEFAULT_POOL_SIZE': str(DEFAULT_POOL_SIZE),
+ 'LISTEN_PORT': '5432',
+ },
+ }
+
+
+def set_enabled(app, enabled: bool) -> Dict:
+ """Save the flag and apply it: `compose up` adds or removes the sidecar
+ (the PostgreSQL container itself is unchanged, so it keeps running)."""
+ from app import db
+ from app.services.docker_service import DockerService
+
+ app.pooler_enabled = bool(enabled)
+ db.session.commit()
+ applied = None
+ if app.root_path and not app.server_id:
+ args = {'compose_file': app.compose_file} if app.compose_file else {}
+ up = DockerService.compose_up(app.root_path, detach=True, **args)
+ applied = bool(up.get('success'))
+ if applied and not enabled:
+ # `up` leaves a service dropped from the override running.
+ DockerService.run(['rm', '-f', container_name(app)], timeout=60)
+ return {'enabled': bool(app.pooler_enabled), 'applied': applied,
+ 'host': container_name(app), 'tradeoff': TRADEOFF}
diff --git a/backend/app/services/service_connection_service.py b/backend/app/services/service_connection_service.py
index 093f798c..5b80108f 100644
--- a/backend/app/services/service_connection_service.py
+++ b/backend/app/services/service_connection_service.py
@@ -138,6 +138,13 @@ class ServiceConnectionService:
properties.update({'host': ctx['host'], 'port': ctx['port'],
'password': password})
+ if protocol == 'postgresql' and getattr(app, 'pooler_enabled', False):
+ # Through the PgBouncer sidecar (plan 86 §D1); same credentials.
+ from app.services.pooler_service import container_name
+ pooled = _URL_PROTOCOLS['postgresql'].format(
+ userinfo=userinfo, **dict(ctx, host=container_name(app), port='5432'))
+ properties.update({'pooledUrl': pooled, 'pooledConnectionString': pooled})
+
for name, raw in (declared.get('properties') or {}).items():
properties[str(name)] = cls._render(str(raw), ctx, variables)
return {'host': ctx['host'], 'port': ctx['port'], 'properties': properties}
diff --git a/backend/migrations/versions/103_pooler_enabled.py b/backend/migrations/versions/103_pooler_enabled.py
new file mode 100644
index 00000000..e20787fd
--- /dev/null
+++ b/backend/migrations/versions/103_pooler_enabled.py
@@ -0,0 +1,19 @@
+"""Opt-in PgBouncer per PostgreSQL app (plan 86 §D1). NULL = off."""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '103_pooler_enabled'
+down_revision = '102_app_attachments'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ inspector = sa.inspect(op.get_bind())
+ # Add-if-missing: the pre-alembic schema sync may already have added it.
+ if 'pooler_enabled' not in {c['name'] for c in inspector.get_columns('applications')}:
+ op.add_column('applications', sa.Column('pooler_enabled', sa.Boolean, nullable=True))
+
+
+def downgrade():
+ op.drop_column('applications', 'pooler_enabled')
diff --git a/backend/tests/test_pooler.py b/backend/tests/test_pooler.py
new file mode 100644
index 00000000..1fd2233d
--- /dev/null
+++ b/backend/tests/test_pooler.py
@@ -0,0 +1,79 @@
+"""PgBouncer beside an installed PostgreSQL (plan 86 §D1). Hermetic half; the
+real round trip is test_real_pooler_docker.py."""
+import json
+
+import pytest
+import yaml
+
+from app import db
+from app.services import pooler_service
+from app.services.compose_env_service import ComposeEnvService
+from app.services.service_connection_service import SHARED_NETWORK, ServiceConnectionService
+from app.services.template_service import TemplateService
+from tests.factories import make_application
+
+
+def installed(app, tmp_path, monkeypatch):
+ records = {}
+ monkeypatch.setattr(TemplateService, 'get_config', classmethod(
+ lambda cls: {'repos': [], 'installed': records}))
+
+ def make(name, template_id, variables):
+ root = tmp_path / name
+ root.mkdir()
+ (root / 'docker-compose.yml').write_text(yaml.safe_dump({'services': {'app': {'image': 'x'}}}))
+ (root / '.serverkit-template.json').write_text(json.dumps(
+ {'template_id': template_id, 'variables': variables}))
+ row = make_application(db, name=name, root_path=str(root))
+ records[str(row.id)] = {'template_id': template_id}
+ return row
+ return make
+
+
+def test_pooling_adds_a_pgbouncer_service_and_a_pooled_url(installed):
+ pg = installed('pg', 'postgresql', {'DB_PASSWORD': 'pa$$', 'DB_NAME': 'shop'})
+ assert 'pooledUrl' not in ServiceConnectionService.spec(pg)['properties']
+ assert 'pgbouncer' not in (ComposeEnvService.render_override(pg.root_path)['content'] or '')
+
+ pg.pooler_enabled = True
+ db.session.commit()
+
+ override = yaml.safe_load(ComposeEnvService.render_override(pg.root_path)['content'])
+ bouncer = override['services']['pgbouncer']
+ assert bouncer['image'] == pooler_service.POOLER_IMAGE
+ assert bouncer['container_name'] == 'pg-pooler'
+ assert bouncer['environment']['DB_HOST'] == 'app'
+ assert bouncer['environment']['POOL_MODE'] == 'transaction'
+ assert bouncer['environment']['DB_PASSWORD'] == 'pa$$$$', 'compose would interpolate $'
+ assert 'ports' not in bouncer
+ assert bouncer['networks'] == {'default': {}, SHARED_NETWORK: {}}
+ props = ServiceConnectionService.spec(pg)['properties']
+ assert props['pooledUrl'] == 'postgresql://postgres:pa%24%24@pg-pooler:5432/shop'
+ assert props['connectionString'].startswith('postgresql://postgres:pa%24%24@pg:5432/')
+
+
+def test_only_postgres_engines_get_a_pooler(installed):
+ cache = installed('cache', 'redis', {'DB_PASSWORD': 'x'})
+ cache.pooler_enabled = True
+ db.session.commit()
+ assert not pooler_service.is_postgres_engine(cache)
+ assert 'pgbouncer' not in (ComposeEnvService.render_override(cache.root_path)['content'] or '')
+
+
+def test_api(installed, client, auth_headers, monkeypatch):
+ pg = installed('pg', 'postgresql', {'DB_PASSWORD': 'x'})
+ cache = installed('cache', 'redis', {'DB_PASSWORD': 'x'})
+ monkeypatch.setattr('app.services.docker_service.DockerService.compose_up',
+ classmethod(lambda cls, path, **kw: {'success': True}))
+ got = client.get(f'/api/v1/apps/{pg.id}/pooler', headers=auth_headers).get_json()
+ assert got['available'] is True and got['enabled'] is False and 'LISTEN' in got['tradeoff']
+ assert client.get(f'/api/v1/apps/{cache.id}/pooler',
+ headers=auth_headers).get_json()['available'] is False
+
+ put = client.put(f'/api/v1/apps/{pg.id}/pooler', json={'enabled': True}, headers=auth_headers)
+ assert put.status_code == 200 and put.get_json()['applied'] is True
+ assert client.put(f'/api/v1/apps/{pg.id}/pooler', json={'enabled': 'yes'},
+ headers=auth_headers).status_code == 400
+ assert client.put(f'/api/v1/apps/{cache.id}/pooler', json={'enabled': True},
+ headers=auth_headers).status_code == 400
diff --git a/backend/tests/test_real_pooler_docker.py b/backend/tests/test_real_pooler_docker.py
new file mode 100644
index 00000000..59bd06aa
--- /dev/null
+++ b/backend/tests/test_real_pooler_docker.py
@@ -0,0 +1,114 @@
+"""PgBouncer beside a REAL PostgreSQL (plan 86 §D1).
+
+The bundled PostgreSQL template is rendered with the panel's rules; turning
+pooling on adds the sidecar through the managed override. A separate project
+that only has ``pooledUrl`` from fromService queries through the pooler (its
+host is the pooler's name, so an answer proves the path), and turning pooling
+off removes the sidecar while PostgreSQL keeps running.
+
+ SERVERKIT_DOCKER_BUILDS=1 pytest tests -m docker_builds
+"""
+import json
+import os
+import shutil
+import subprocess
+import time
+import uuid
+
+import pytest
+import yaml
+
+from app import db
+from app.services import pooler_service
+from app.services.compose_env_service import ComposeEnvService
+from app.services.env_service import EnvService
+from app.services.template_service import TemplateService
+from tests.factories import make_application
+
+
+def _docker_ready() -> bool:
+ if shutil.which('docker') is None:
+ return False
+ try:
+ return subprocess.run(['docker', 'info'], capture_output=True,
+ timeout=20).returncode == 0
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+
+
+pytestmark = [
+ pytest.mark.docker_builds,
+ pytest.mark.skipif(os.environ.get('SERVERKIT_DOCKER_BUILDS') != '1',
+ reason='docker-builds leg; opt in with SERVERKIT_DOCKER_BUILDS=1'),
+ pytest.mark.skipif(not _docker_ready(), reason='docker daemon not reachable'),
+]
+
+SECRET = 'p@ss:w/rd#1%'
+
+
+def _running(name):
+ out = subprocess.run(['docker', 'ps', '--filter', f'name=^{name}$', '--format', '{{.Names}}'],
+ capture_output=True, text=True).stdout
+ return name in out.split()
+
+
+def test_an_app_queries_postgres_through_the_pooler(app, tmp_path, monkeypatch):
+ suffix = uuid.uuid4().hex[:8]
+ pg_name, client_name = f'skc-pg-{suffix}', f'skc-api-{suffix}'
+ installed = {}
+ monkeypatch.setattr(TemplateService, 'get_config', classmethod(
+ lambda cls: {'repos': [], 'installed': installed}))
+ template = TemplateService.get_template('postgresql')['template']
+ variables = {'APP_NAME': pg_name, 'IMAGE_TAG': '16', 'BIND_ADDRESS': '127.0.0.1',
+ 'PORT': '0', 'DB_PASSWORD': SECRET, 'DB_NAME': 'shop'}
+ root = tmp_path / pg_name
+ root.mkdir()
+ compose = yaml.safe_load(TemplateService.generate_compose(template, variables))
+ for svc in compose['services'].values():
+ svc.pop('ports', None)
+ (root / 'docker-compose.yml').write_text(yaml.safe_dump(compose))
+ (root / '.serverkit-template.json').write_text(json.dumps(
+ {'template_id': 'postgresql', 'variables': variables}))
+ pg = make_application(db, name=pg_name, root_path=str(root),
+ compose_file='docker-compose.yml')
+ installed[str(pg.id)] = {'template_id': 'postgresql'}
+
+ client_root = tmp_path / client_name
+ client_root.mkdir()
+ (client_root / 'docker-compose.yml').write_text(yaml.safe_dump({'services': {'api': {
+ 'image': 'postgres:16-alpine',
+ 'command': ['sh', '-c', 'for i in $$(seq 30); do '
+ 'psql "$$DATABASE_URL" -Atc "select 40 + 2" && exit 0; sleep 2; done; exit 1'],
+ }}}))
+ client = make_application(db, name=client_name, root_path=str(client_root))
+ _v, _c, error = EnvService.set_env_reference(
+ client.id, 'DATABASE_URL', {'kind': 'service', 'service': pg_name, 'property': 'pooledUrl'})
+ assert error is None
+
+ pg_files = ['-f', str(root / 'docker-compose.yml'),
+ '-f', str(root / ComposeEnvService.OVERRIDE_NAME)]
+ client_files = ['-f', str(client_root / 'docker-compose.yml'),
+ '-f', str(client_root / ComposeEnvService.OVERRIDE_NAME)]
+ try:
+ result = pooler_service.set_enabled(pg, True)
+ assert result['applied'] is True, result
+ assert _running(pooler_service.container_name(pg))
+ assert EnvService.get_effective_env(client.id)['DATABASE_URL'].startswith(
+ f'postgresql://postgres:')
+
+ ComposeEnvService.refresh_for_project(str(client_root))
+ ran = subprocess.run(['docker', 'compose', '-p', client_name, *client_files,
+ 'run', '--rm', 'api'], capture_output=True, text=True, timeout=300)
+ assert ran.stdout.strip().splitlines()[-1:] == ['42'], ran.stdout + ran.stderr
+
+ off = pooler_service.set_enabled(pg, False)
+ assert off['applied'] is True
+ assert not _running(pooler_service.container_name(pg))
+ assert _running(pg_name), 'turning pooling off must not stop PostgreSQL'
+ finally:
+ subprocess.run(['docker', 'compose', '-p', client_name, *client_files, 'down', '-v'],
+ capture_output=True, timeout=180)
+ subprocess.run(['docker', 'rm', '-f', pooler_service.container_name(pg)],
+ capture_output=True, timeout=60)
+ subprocess.run(['docker', 'compose', '-p', pg_name, *pg_files, 'down', '-v'],
+ capture_output=True, timeout=180)
diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.md
index a3564aad..a95b0815 100644
--- a/docs/API_SURFACE.md
+++ b/docs/API_SURFACE.md
@@ -178,6 +178,7 @@ Regenerate (backend/):
- `GET /apps/{app_id}/grants`
- `GET /apps/{app_id}/linked`
- `GET /apps/{app_id}/logs`
+- `GET /apps/{app_id}/pooler`
- `GET /apps/{app_id}/previews`
- `GET /apps/{app_id}/previews/settings`
- `GET /apps/{app_id}/private-url`
@@ -1288,6 +1289,7 @@ Regenerate (backend/):
- `PUT /apps/{app_id}/env/{key}`
- `PUT /apps/{app_id}/environment`
- `PUT /apps/{app_id}/micro-cache`
+- `PUT /apps/{app_id}/pooler`
- `PUT /apps/{app_id}/previews/settings`
- `PUT /apps/{app_id}/private-url`
- `PUT /apps/{app_id}/resources`
diff --git a/frontend/src/components/service-detail/OverviewTab.jsx b/frontend/src/components/service-detail/OverviewTab.jsx
index d75cb656..52f1ca99 100644
--- a/frontend/src/components/service-detail/OverviewTab.jsx
+++ b/frontend/src/components/service-detail/OverviewTab.jsx
@@ -10,6 +10,7 @@ import BandwidthSparkline from '../BandwidthSparkline';
import ScheduledTasksCard from '../ScheduledTasksCard';
import RequestMetricsCard from './RequestMetricsCard';
import AttachmentsCard from './AttachmentsCard';
+import PoolerCard from './PoolerCard';
import { KpiBand, MetricCard, Pill, Gauge, EnvTag, statusKind } from '@/components/ds';
import { usePolling } from '@/hooks/usePolling';
import { useTranslation } from 'react-i18next';
@@ -334,6 +335,9 @@ const OverviewTab = ({ app, deployConfig }) => {
{/* Cache / storage / queue this app uses (plan 86 §C4) */}
<AttachmentsCard app={app} />
+ {/* PgBouncer beside an installed PostgreSQL (plan 86 §D1) */}
+ <PoolerCard app={app} />
+
{/* Recent Deployments */}
<div className="overview-tab__card overview-tab__card--full">
<div className="overview-tab__card-header-row">
diff --git a/frontend/src/components/service-detail/PoolerCard.jsx b/frontend/src/components/service-detail/PoolerCard.jsx
new file mode 100644
index 00000000..506eac9b
--- /dev/null
+++ b/frontend/src/components/service-detail/PoolerCard.jsx
@@ -0,0 +1,65 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import api from '../../services/api';
+import { Switch } from '@/components/ui/switch';
+import { useToast } from '../../contexts/useToast.js';
+
+// Opt-in PgBouncer beside an installed PostgreSQL (plan 86 §D1). Renders only
+// for PostgreSQL installs. Apps keep the direct connection unless they switch
+// their reference to `pooledUrl`, because transaction pooling breaks session
+// features, and that tradeoff is stated where the choice is made.
+export default function PoolerCard({ app }) {
+ const { t } = useTranslation();
+ const toast = useToast();
+ const [state, setState] = useState(null);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ api.getAppPooler(app.id)
+ .then((data) => { if (!cancelled) setState(data); })
+ .catch(() => {});
+ return () => { cancelled = true; };
+ }, [app.id]);
+
+ if (!state?.available) return null;
+
+ async function toggle(next) {
+ setSaving(true);
+ try {
+ const data = await api.setAppPooler(app.id, next);
+ setState((prev) => ({ ...prev, enabled: data.enabled }));
+ if (data.applied === false) {
+ toast.warning(t('app.pooler.savedNotApplied', 'Saved, but the pooler could not be started. Check the containers.'));
+ } else {
+ toast.success(next
+ ? t('app.pooler.on', 'Pooler running at {{host}}:5432.', { host: data.host })
+ : t('app.pooler.off', 'Pooler removed.'));
+ }
+ } catch (err) {
+ toast.error(err.message);
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <div className="overview-tab__card overview-tab__card--full pooler">
+ <div className="overview-tab__card-header-row">
+ <h3 className="overview-tab__card-title">{t('app.pooler.title', 'Connection pooling')}</h3>
+ <Switch
+ checked={Boolean(state.enabled)}
+ onCheckedChange={toggle}
+ disabled={saving}
+ aria-label={t('app.pooler.title', 'Connection pooling')}
+ />
+ </div>
+ <p className="pooler__hint">
+ {t('app.pooler.hint', 'Runs PgBouncer in transaction mode beside this database, so many app connections share a few server connections. Apps opt in by referencing pooledUrl instead of connectionString.')}
+ </p>
+ <p className="pooler__tradeoff">
+ {t('app.pooler.tradeoff', 'Transaction pooling breaks session features: prepared statements in some drivers, LISTEN/NOTIFY, advisory locks and session SET. Apps keep the direct connection unless they switch.')}
+ </p>
+ </div>
+ );
+}
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 91a93e70..655015f0 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -3802,6 +3802,14 @@
"pipelineStrip": {
"deploymentSteps": "Deployment steps"
},
+ "pooler": {
+ "hint": "Runs PgBouncer in transaction mode beside this database, so many app connections share a few server connections. Apps opt in by referencing pooledUrl instead of connectionString.",
+ "off": "Pooler removed.",
+ "on": "Pooler running at {{host}}:5432.",
+ "savedNotApplied": "Saved, but the pooler could not be started. Check the containers.",
+ "title": "Connection pooling",
+ "tradeoff": "Transaction pooling breaks session features: prepared statements in some drivers, LISTEN/NOTIFY, advisory locks and session SET. Apps keep the direct connection unless they switch."
+ },
"previewDrawer": {
"copyPath": "Copy path",
"downloadFile": "Download File",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 1e109f8f..c89a1369 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -6761,6 +6761,14 @@
"rows": "Filas",
"topQueries": "Consultas principales por tiempo total",
"total": "Total"
+ },
+ "pooler": {
+ "hint": "Ejecuta PgBouncer en modo transacción junto a esta base de datos, para que muchas conexiones de la app compartan unas pocas conexiones del servidor. Las apps lo usan referenciando pooledUrl en lugar de connectionString.",
+ "off": "Pooler eliminado.",
+ "on": "Pooler en marcha en {{host}}:5432.",
+ "savedNotApplied": "Guardado, pero no se pudo iniciar el pooler. Revisa los contenedores.",
+ "title": "Agrupación de conexiones",
+ "tradeoff": "La agrupación por transacción rompe funciones de sesión: sentencias preparadas en algunos drivers, LISTEN/NOTIFY, bloqueos consultivos y SET de sesión. Las apps mantienen la conexión directa salvo que cambien."
}
},
"auth": {
diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.js
index 3d0f9ca8..63df99f2 100644
--- a/frontend/src/services/api/apps.js
+++ b/frontend/src/services/api/apps.js
@@ -555,3 +555,12 @@ export async function attachService(appId, kind, serviceAppId) {
export async function detachService(appId, attachmentId) {
return this.request(`/apps/${appId}/attachments/${attachmentId}`, { method: 'DELETE' });
}
+
+// Opt-in PgBouncer beside an installed PostgreSQL (plan 86 §D1).
+export async function getAppPooler(appId) {
+ return this.request(`/apps/${appId}/pooler`);
+}
+
+export async function setAppPooler(appId, enabled) {
+ return this.request(`/apps/${appId}/pooler`, { method: 'PUT', body: { enabled } });
+}
diff --git a/frontend/src/styles/pages/_bandwidth.scss b/frontend/src/styles/pages/_bandwidth.scss
index 1b74121d..e6b96d7d 100644
--- a/frontend/src/styles/pages/_bandwidth.scss
+++ b/frontend/src/styles/pages/_bandwidth.scss
@@ -244,3 +244,16 @@
color: var(--red);
}
}
+
+// Service detail Overview: Connection pooling card (plan 86 §D1).
+// Component: service-detail/PoolerCard.
+.pooler {
+ &__hint,
+ &__tradeoff {
+ margin: 0 0 6px;
+ font-size: 12.5px;
+ color: var(--text-dim);
+ }
+
+ &__tradeoff { color: var(--text-faint); }
+}