Skip to main content

Synapse on Google Cloud Run

Synapse on Google Cloud Run

Synapse is the reference Matrix homeserver — the open-source, Apache 2.0-licensed Python server for the Matrix protocol, an open standard for decentralized, federated real-time communication (secure chat and VoIP). This module deploys Synapse on Cloud Run v2 on top of the App_CloudRun foundation, which provisions and manages the shared Google Cloud infrastructure. Users connect to the homeserver with a Matrix client such as the Element web app.

This guide focuses on the cloud services Synapse uses and how to explore and operate them from the Google Cloud Console and the command line. For the mechanics common to every Cloud Run application — service identity, ingress and load balancing, scaling and concurrency, CI/CD, Cloud Armor, IAP, Binary Authorization, VPC Service Controls, backups, and the deployment lifecycle — refer to the App_CloudRun foundation guide rather than repeating them here.


1. Overview

Synapse runs as a Python container on Cloud Run v2. The deployment wires together a focused set of Google Cloud services:

CapabilityGoogle Cloud serviceNotes
ComputeCloud Run v2Python homeserver, 2 vCPU / 4 GiB by default, kept warm (min_instance_count = 1)
DatabaseCloud SQL for PostgreSQL 15Required — Synapse does not support MySQL; database must use C collation
Object storageCloud StorageA dedicated data bucket provisioned automatically
Persistent filesNFS (Filestore)Signing key + media repository under the data directory; enabled by default
SecretsSecret ManagerAuto-generated registration shared secret; database password
IngressCloud Run URL / Cloud Load BalancingDefault run.app URL; optional external HTTPS load balancer + custom domain

Sensible defaults worth knowing up front:

  • PostgreSQL 15 is mandatory, with C collation. The database engine is fixed by the shared application layer, and the first-deploy db-init job creates the database with LC_COLLATE='C' LC_CTYPE='C' — Synapse refuses to start against any other collation.
  • Synapse self-manages its schema. There is no separate migrate job; Synapse creates and upgrades its own schema automatically on every start.
  • homeserver.yaml and the signing key are generated on first boot. The cloud entrypoint generates the config plus a persistent signing key into the data directory and wires the platform PostgreSQL before starting Synapse.
  • The signing key must persist. Regenerating it breaks federation and invalidates all device sessions, so the data directory is backed by persistent NFS storage (enable_nfs = true by default).
  • server_name is fixed at matrix.local. It is the domain baked into every user ID (@user:server_name) and into federation. Synapse_CloudRun does not expose a server_name input — the value always comes from Synapse_Common's default, so a production deployment needing a real domain currently requires overriding the Common module directly.
  • Listens on port 8008. The client + federation HTTP listener is set in the generated config; health is served unauthenticated at /health.
  • Kept warm, not scaled to zero. A homeserver maintains federation, background retention, and presence between requests, so min_instance_count = 1 and cpu_always_allocated = true are the defaults. Scale-to-zero is a poor fit for a federating homeserver (a cold instance misses inbound federation traffic).
  • Redis is not used. Synapse runs a single main process backed entirely by PostgreSQL.
  • Admin users are created out-of-band. Open self-service registration is off by default; create users with register_new_matrix_user and the registration shared secret in Secret Manager.

2. Google Cloud Services & How to Explore Them

All commands assume PROJECT and REGION are set. Service and resource names are reported in the deployment Outputs.

A. Cloud Run — the Synapse service

Synapse runs as a Cloud Run v2 service. Each deployment creates an immutable revision; traffic can be split across revisions for safe rollouts.

  • Console: Cloud Run → select the service for revisions, traffic, logs, and metrics.
  • CLI:
    gcloud run services list --project "$PROJECT" --region "$REGION"
    gcloud run services describe <service-name> --project "$PROJECT" --region "$REGION"
    gcloud run revisions list --service <service-name> --project "$PROJECT" --region "$REGION"

See App_CloudRun for scaling, concurrency, execution environment, and traffic splitting.

B. Cloud SQL for PostgreSQL 15

Synapse stores all homeserver state (accounts, rooms, events, device keys, federation state) in a managed Cloud SQL for PostgreSQL 15 instance. The service connects privately through the Cloud SQL Auth Proxy over a Unix socket; no public IP is exposed. On first deploy a db-init Job creates the application database with C collation and the application user.

  • Console: SQL → select the instance for connections, backups, flags, metrics.
  • CLI:
    gcloud sql instances list --project "$PROJECT"
    gcloud sql instances describe <instance-name> --project "$PROJECT"
    gcloud sql connect <instance-name> --user=<db-user> --database=<db-name> --project "$PROJECT"
    # Verify the mandatory collation:
    # SELECT datname, datcollate, datctype FROM pg_database WHERE datname = '<db-name>';

The instance name, database, user, and password secret are in the Outputs. See App_CloudRun for the connection model, backups, and password rotation.

C. Cloud Storage & the persistent data directory

A dedicated Cloud Storage data bucket is provisioned automatically. Synapse's own runtime state — homeserver.yaml, the conf.d overrides, the signing key, and the media repository — lives under the data directory (SYNAPSE_DATA_DIR = /data), which is backed by the NFS (Filestore) volume mounted at the configured mount path.

  • Console: Cloud Storage → Buckets; Filestore → Instances.
  • CLI:
    gcloud storage buckets list --project "$PROJECT"
    gcloud filestore instances list --project "$PROJECT"

See App_CloudRun for GCS Fuse, NFS, and CMEK options.

D. Secret Manager

A registration shared secret is generated automatically and stored in Secret Manager; it backs register_new_matrix_user for out-of-band account creation. The database password is managed separately by the foundation.

  • Console: Security → Secret Manager.
  • CLI:
    gcloud secrets list --project "$PROJECT" --filter="name~synapse"
    gcloud secrets versions access latest --secret=<secret-name> --project "$PROJECT"

See App_CloudRun for injection and rotation details.

E. Networking & ingress

The service is reachable at its run.app URL by default. Matrix client and federation traffic require public reachability, so ingress_settings = "all" is the default. An external HTTPS load balancer with a custom domain (recommended for production), Cloud CDN for media, and Cloud Armor can be layered on.

  • Console: Cloud Run (service URL); Network services → Load balancing.
  • CLI:
    gcloud run services describe <service-name> --region "$REGION" --format='value(status.url)'
    gcloud compute addresses list --project "$PROJECT"

See App_CloudRun.

F. Cloud Logging & Monitoring

Container logs flow to Cloud Logging; Cloud Run and Cloud SQL metrics flow to Cloud Monitoring, with optional uptime checks and alert policies.

  • Console: Logging → Logs Explorer; Monitoring → Dashboards / Alerting.
  • CLI:
    gcloud run services logs read <service-name> --project "$PROJECT" --region "$REGION" --limit 50

3. Synapse Application Behaviour

  • First-deploy database setup. A db-init Job runs db-init.sh using postgres:15-alpine. It connects through the Cloud SQL Auth Proxy and idempotently creates the application role and the database with C collation (LC_COLLATE='C' LC_CTYPE='C' TEMPLATE template0), recreating an empty wrong-collation database if the foundation created one first. The job is safe to re-run.
  • No migrate job — schema self-managed. Synapse creates and upgrades its schema on every start, so upgrading the application version applies schema changes without a separate migration step.
  • Config + signing key generated on first boot. The cloud entrypoint generates homeserver.yaml and a persistent signing key into /data, writes a conf.d snippet wiring PostgreSQL and the 0.0.0.0:8008 listener, then execs Synapse. The signing key is generated only once — keep /data on persistent storage.
  • server_name is fixed at matrix.local. Synapse_CloudRun does not expose a server_name input (it always uses the Synapse_Common default); changing the underlying value after first boot invalidates every user ID, device session, and federation relationship.
  • Health path. The default startup_probe/liveness_probe target / (root). Synapse also serves an unauthenticated /health endpoint (OK) that can be used by overriding those probe paths. Confirm the client API is serving with GET /_matrix/client/versions:
    curl -s "$(gcloud run services describe <service-name> --region "$REGION" \
    --format='value(status.url)')/_matrix/client/versions"
  • Create the first admin user with the Matrix registration tool, using the shared secret from Secret Manager:
    register_new_matrix_user -c homeserver.yaml -u admin -a https://<your-domain>
  • Inspect job execution:
    gcloud run jobs list --project "$PROJECT" --region "$REGION"
    gcloud run jobs executions list --job <job-name> --project "$PROJECT" --region "$REGION"

4. Configuration Variables

Variables are grouped exactly as they appear on the deployment platform. Only settings specific to or notable for Synapse are listed; every other input is inherited from App_CloudRun with its standard behaviour.

Group 1 — Project & Identity

VariableDefaultDescription
project_id(required)Target Google Cloud project.
regionus-central1Region for the service and regional resources.

Group 2 — Deployment Environment

VariableDefaultDescription
tenant_deployment_iddemoShort suffix that makes resource names unique per environment.
support_users[]Emails granted project access and monitoring alerts.
resource_labels{}Labels applied to all resources.

Group 3 — Application Identity

VariableDefaultDescription
application_namesynapseBase name for resources. Do not change after first deploy.
display_nameSynapseHuman-readable name shown in the Console.
description(set)Service description.
application_versionlatestSynapse image tag; pin to a specific release (e.g. v1.119.0) in production.

Group 4 — Runtime & Scaling

VariableDefaultDescription
deploy_applicationtrueSet false to provision infrastructure only.
cpu_limit2000mCPU per instance; 2 vCPU recommended.
memory_limit4GiMemory per instance; minimum 2 GiB for reliable operation.
min_instance_count1Keeps the homeserver warm for federation and background tasks. Do not set 0 for a federating server.
max_instance_count5Autoscaling upper bound.
cpu_always_allocatedtrueAlways-allocated CPU so background federation/retention keeps running between requests.
container_port8008Synapse's client + federation HTTP listener.
execution_environmentgen2Gen2 required for NFS/GCS mounts.
timeout_seconds300Maximum request duration.
enable_cloudsql_volumetrueCloud SQL Auth Proxy for socket connections.
container_image_sourcecustomThin custom build FROM matrixdotorg/synapse.
enable_image_mirroringtrueMirror the Synapse base image into Artifact Registry.

Group 5 — Access & Ingress Control

VariableDefaultDescription
ingress_settingsallRequired for public Matrix client and federation traffic.
vpc_egress_settingPRIVATE_RANGES_ONLYRoute only RFC 1918 traffic via VPC.
enable_iapfalseRequire Google sign-in. Blocks federation and external clients — use only for admin-only/private homeservers.
iap_authorized_users / iap_authorized_groups[]Who may access through IAP.

Group 6 — Environment Variables & Secrets

VariableDefaultDescription
environment_variables{}Extra non-secret settings. Core SYNAPSE_* values are set automatically.
secret_environment_variables{}Map of env var → Secret Manager secret name.
secret_propagation_delay30Seconds to wait after secret creation before proceeding.
secret_rotation_period2592000sSecret Manager rotation notification frequency.

Group 7 — Backup & Restore

VariableDefaultDescription
backup_schedule0 2 * * *Automated backup cron (UTC).
backup_retention_days7Retention; raise for production/compliance.
enable_backup_import / backup_source / backup_file / backup_formatrestore optionsRestore from a backup on deploy.

Group 8 — CI/CD & Binary Authorization

Standard App_CloudRun Cloud Build / Cloud Deploy integration — see App_CloudRun. Key inputs: enable_cicd_trigger, github_repository_url, github_token, enable_cloud_deploy, enable_binary_authorization.

Group 9 — Custom SQL Scripts

enable_custom_sql_scripts, custom_sql_scripts_bucket, custom_sql_scripts_path, custom_sql_scripts_use_root — run SQL from a GCS bucket after provisioning. See App_CloudRun.

Group 10 — Load Balancer, CDN & Image Retention

VariableDefaultDescription
enable_cloud_armorfalseProvision Global HTTPS LB + Cloud Armor WAF.
admin_ip_ranges[]CIDR ranges exempted from WAF rules.
application_domains[]Custom domain names for the HTTPS load balancer.
enable_cdnfalseEnable Cloud CDN on the HTTPS LB backend (useful for media).
max_images_to_retain / delete_untagged_images / image_retention_days7 / true / 30Artifact Registry cleanup policy.

Group 11 — Storage & Filesystem

VariableDefaultDescription
create_cloud_storagetrueCreate the GCS data bucket.
enable_nfstruePersistent NFS for the data directory (signing key + media).
nfs_mount_path/opt/synapse/storageMount path inside the container.
gcs_volumes[]GCS Fuse volume mounts (requires gen2).
manage_storage_kms_iam / enable_artifact_registry_cmekfalseCMEK options.

Group 12 — Database Backend

VariableDefaultDescription
db_namesynapsePostgreSQL database name. Immutable after first deploy.
db_usersynapseApplication database user. Password auto-generated in Secret Manager.
database_password_length32Generated password length (16–64).
enable_auto_password_rotation / rotation_propagation_delay_secoffDB password rotation.

Group 13 — Jobs & Scheduled Tasks

VariableDefaultDescription
initialization_jobs[]Leave empty to use the built-in db-init job (C-collation database + role).
cron_jobs[]Scheduled Cloud Scheduler + Cloud Run Jobs.

Group 14 — Observability & Health

VariableDefaultDescription
startup_probeHTTP / 60s delayStartup probe. Synapse also serves an unauthenticated /health endpoint that can be used by overriding path.
liveness_probeHTTP /Liveness probe.
uptime_check_config{ enabled=false, path="/" }Optional Cloud Monitoring uptime check.
alert_policies[]Metric alert policies.

Group 21 — Redis

VariableDefaultDescription
enable_redisfalseSynapse uses a PostgreSQL-backed queue/cache — leave false unless externalizing.
redis_host / redis_port / redis_auth"" / 6379 / ""Redis endpoint (only when externalizing).

Group 22 — VPC Service Controls & Audit Logging

VariableDefaultDescription
enable_vpc_scfalseEnforce a VPC-SC perimeter (requires organization_id).
vpc_cidr_ranges / vpc_sc_dry_run(set)Access level CIDRs / dry-run mode.
enable_audit_loggingfalseDetailed Cloud Audit Logs.

5. Outputs

Returned on a successful deployment — the quickest way to locate and explore the running resources.

OutputDescription
service_nameCloud Run service name.
service_urlDefault run.app URL of the service.
service_locationRegion the service runs in.
stage_servicesStage-specific service URLs (Cloud Deploy).
load_balancer_ip / load_balancer_urlExternal HTTPS load balancer IP / URL (when enabled).
database_instance_nameCloud SQL instance name.
database_name / database_userApplication database name / user.
database_password_secretSecret Manager secret holding the DB password.
database_host / database_portDB endpoint / port.
storage_bucketsCreated Cloud Storage buckets.
network_name / network_exists / regionsVPC network, presence, regions.
container_image / container_registryDeployed image and Artifact Registry repo.
monitoring_enabled / monitoring_notification_channels / uptime_check_namesMonitoring status, channels, uptime checks.
initialization_jobsNames of the setup jobs.
deployment_id / tenant_id / resource_prefixNaming identifiers.
project_id / project_numberProject identifiers.
cicd_enabled / github_repository_url / github_repository_owner / github_repository_name / cicd_configurationCI/CD status and details.
artifact_registry_repository / cloudbuild_trigger_name / cloudbuild_trigger_idRegistry and build trigger.
vpc_sc_enabled / vpc_sc_perimeter_name / vpc_sc_dry_run_modeVPC-SC status.
audit_logging_enabled / artifact_registry_cmek_enabledAudit logging and CMEK status.

6. Configuration Pitfalls & Sensible Defaults

Risk: Critical (data loss / outage / security) — High (service degraded) — Medium (cost or partial degradation) — Low (minor).

Inherited plan-time validation. This module passes its configuration through the App_CloudRun foundation engine, which validates values and combinations at plan time — a read replica without its primary, IAP with no authorized identities, a gen1 runtime with NFS/GCS mounts, an out-of-range redis_port/backup_retention_days. Invalid configuration fails the plan with a clear, named error before any resource is created, so most mistakes below are caught up front rather than at apply or runtime.

SettingSensible valueRiskConsequence if wrong
server_name (fixed matrix.local)Not exposed as a Synapse_CloudRun inputCriticalReal federation and durable user IDs need a custom domain; this module has no server_name variable, so production use currently requires overriding Synapse_Common directly. Changing the underlying value after first boot invalidates every user ID, device session, and federation relationship.
Signing key persistence (enable_nfs)trueCriticalIf the data directory is not persistent, a restart regenerates the signing key, breaking federation and invalidating all device sessions.
Database collation (db-init)C (automatic)CriticalSynapse refuses to start against any non-C collation; do not bypass the db-init job.
db_name / db_userSet onceCriticalImmutable after first deploy; renaming recreates the DB/user and destroys all data.
enable_backup_importfalse unless restoringCriticalEnabling without a valid backup_uri fails the import job.
min_instance_count1HighScale-to-zero leaves a federating homeserver cold — it misses inbound federation traffic and background tasks stall.
cpu_always_allocatedtrueHighRequest-based billing throttles CPU to ~0 between requests, stalling background retention and federation retries.
memory_limit4Gi (≥ 2 GiB)HighBelow 2 GiB Synapse OOMs under real room/federation load.
ingress_settingsallHighinternal blocks Matrix clients and all federation.
enable_iaponly for private serversHighIAP blocks federation and external clients; use only for admin-only deployments.
container_port8008HighSynapse listens on 8008; a mismatched port makes the probe hit a dead port and the revision never becomes Ready.
Probe path/ (default) or /healthHighPointing startup_probe/liveness_probe at an authenticated Matrix API path returns 401/403 and the revision never becomes Ready.
backup_retention_days7 (raise for prod)MediumToo short for compliance retention.
enable_cdnenable for media-heavy serversMediumMedia downloads are served directly from the instance without CDN offload.

For the foundation behaviour referenced throughout — service identity, scaling and concurrency, ingress and load balancing, CI/CD, Cloud Armor, IAP, Binary Authorization, VPC-SC, backups, and image mirroring — see App_CloudRun. Synapse-specific application configuration shared with the GKE variant is described in Synapse_Common.