Nov 19, 20267 min read

Database per Service: How Microservices Own Their Data

What the database-per-service pattern requires, the isolation levels from shared schema to separate servers, how to query across services without shared tables, and an event-fed read model in Go.

Illustration for Database per Service: How Microservices Own Their Data

The moment two services read the same table, neither can change it alone. A renamed column becomes a coordinated deploy, a slow query in one service locks rows the other needs, and the team boundary you drew on the architecture diagram stops existing in the database.

The database-per-service pattern fixes that by giving every table exactly one owner. This guide covers what that means in Postgres, how to answer queries that span services, and the costs you take on.

Database per service at a glance

ApproachIsolationWhat it costs
Shared tablesNoneCoupled schemas and deploys
Schema per service, one serverOwnership enforced by rolesShared CPU, memory and connections
Database per service, one serverSeparate catalogs and connection limitsStill one failure domain
Server per serviceFull isolation, independent scalingMore instances to run, back up and pay for
Cross-service queriesThrough APIs or event-fed read modelsEventual consistency, duplicated fields

Why should services not share tables?

A shared table works as an API with no versioning, and Martin Fowler calls this the integration database: every consumer depends on the exact columns, so every schema change is a negotiation, and the database becomes the place where teams step on each other. Performance couples too, since a heavy report in one service competes for the same locks, buffers and connection slots as checkout.

With a single owner, the customers service can split name into two columns, add an index or move to another engine, and as long as its API and events keep their shape, nothing else changes.

How do you enforce ownership in Postgres?

The cheapest boundary is a schema and a login role per service on one server. Schemas namespace the tables, and privileges enforce the boundary instead of leaving it as a convention:

-- One database, one schema and one login role per service. -- Set each role's password from the secret manager, not in this script. CREATE ROLE customers_svc LOGIN; CREATE ROLE billing_svc LOGIN; CREATE SCHEMA customers AUTHORIZATION customers_svc; CREATE SCHEMA billing AUTHORIZATION billing_svc; -- Nobody else gets in by default. REVOKE ALL ON SCHEMA customers FROM PUBLIC; REVOKE ALL ON SCHEMA billing FROM PUBLIC; -- Each role resolves unqualified table names to its own schema. ALTER ROLE customers_svc SET search_path = customers; ALTER ROLE billing_svc SET search_path = billing;

Connected as billing_svc, CREATE TABLE invoices lands in the billing schema, and SELECT * FROM customers.customers fails with permission denied for schema customers. Each service runs its own migrations against its own schema with its own credentials.

Move to separate databases when you want per-service connection limits and backups, and to separate servers when one service's load, engine choice or availability target differs enough to justify another instance to operate.

How do you query data that spans services?

API composition. The caller asks each owner and merges the results, the API composition pattern. It is simple and always current, but latency adds up, one slow owner slows every page, and filtering or sorting across services happens in memory.

Event-fed read models. The owner publishes an event on every change, and each consumer stores the fields it needs in its own tables. Billing keeps a customer_contacts table with name and email, updated from CustomerUpdated events, and joins it to invoices with plain SQL. Reads are fast and local, at the cost of eventual consistency and a copy of a few fields.

Change data capture. When the owner cannot publish events from code, a CDC tool such as Debezium streams row changes from the write-ahead log. It works with legacy services, but consumers then depend on the owner's table layout again, so map changes to stable events before other services see them.

What does database per service cost?

Transactions stop at the service boundary, so an order that reserves stock and charges a card across two services needs a saga, with compensating steps instead of a rollback. Writes that must also publish an event need a transactional outbox, or a crash between the commit and the publish loses the event. Reporting needs its own store, fed from events or CDC. And every service needs its own migrations, credentials and backups, which is where the operational cost of the pattern sits.

Database per service with Encore

Encore

Encore is a backend framework with built-in infrastructure, and a database is declared inside the service that owns it. Each declaration gets its own migrations and connection pool, and services reach each other's data through typed API calls or Pub/Sub events.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop --example=hello-world$ cd shop && mkdir -p customers/migrations billing/migrations

The customers service owns its table and publishes a change event on every write:

// customers/customers.go package customers import ( "context" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) // Owned by the customers service. Other services ask for data through its // API or keep a copy from its events. var db = sqldb.NewDatabase("customers", sqldb.DatabaseConfig{Migrations: "./migrations"}) type CustomerUpdated struct { ID string `json:"id"` Name string `json:"name"` Email string `json:"email"` } // Other services learn about changes from events, not from the table. var Updated = pubsub.NewTopic[*CustomerUpdated]("customer-updated", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type Customer struct { ID string `json:"id"` Name string `json:"name"` Email string `json:"email"` } //encore:api private method=PUT path=/customers/:id func Upsert(ctx context.Context, id string, c *Customer) error { _, err := db.Exec(ctx, ` INSERT INTO customers (id, name, email) VALUES ($1, $2, $3) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email`, id, c.Name, c.Email) if err != nil { return err } _, err = Updated.Publish(ctx, &CustomerUpdated{ID: id, Name: c.Name, Email: c.Email}) return err } //encore:api private method=GET path=/customers/:id func Get(ctx context.Context, id string) (*Customer, error) { c := &Customer{ID: id} err := db.QueryRow(ctx, `SELECT name, email FROM customers WHERE id = $1`, id).Scan(&c.Name, &c.Email) return c, err }

Billing has its own database with an invoices table and a customer_contacts read model, kept current by a subscription:

// billing/billing.go package billing import ( "context" "encore.dev/pubsub" "encore.dev/storage/sqldb" "encore.app/customers" ) var db = sqldb.NewDatabase("billing", sqldb.DatabaseConfig{Migrations: "./migrations"}) // Keep billing's copy of customer contact details current. var _ = pubsub.NewSubscription(customers.Updated, "billing-contacts", pubsub.SubscriptionConfig[*customers.CustomerUpdated]{ Handler: func(ctx context.Context, e *customers.CustomerUpdated) error { _, err := db.Exec(ctx, ` INSERT INTO customer_contacts (customer_id, name, email) VALUES ($1, $2, $3) ON CONFLICT (customer_id) DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email`, e.ID, e.Name, e.Email) return err }, }, ) type InvoiceView struct { ID int64 `json:"id"` AmountCents int64 `json:"amount_cents"` Name string `json:"name"` Email string `json:"email"` } // The "join" happens inside billing's own database, with no call to customers. // //encore:api public method=GET path=/invoices/:id func GetInvoice(ctx context.Context, id int64) (*InvoiceView, error) { v := &InvoiceView{ID: id} err := db.QueryRow(ctx, ` SELECT i.amount_cents, c.name, c.email FROM invoices i JOIN customer_contacts c ON c.customer_id = i.customer_id WHERE i.id = $1`, id).Scan(&v.AmountCents, &v.Name, &v.Email) return v, err }

encore run starts Postgres locally, creates both databases and applies each service's migrations. The upsert is idempotent, so redelivered events are harmless, and the outbox package closes the gap between the customer write and the publish. Sharing a database is still possible with sqldb.Named, but it is an explicit line of code that shows up in review and in the architecture diagram, not a connection string copied between services.

On deploy, each database is created on RDS or Cloud SQL in your own account, and Encore provisions an IAM role for the service, or a service account on GCP. A coding agent extending billing reads the subscription and the read model in one package and has no path to quietly query the customers table instead.

Best fit: Go and TypeScript teams splitting a system into services who want ownership of data enforced by the code structure, with local databases per service from the first commit.

Frequently asked questions

What is the database-per-service pattern?

Each service owns its data and is the only code that reads or writes its tables. Other services get that data through the owner's API or from events it publishes. The physical setup can be a separate schema, a separate database or a separate server, as long as no other service queries the tables directly.

Do I need a separate database server for each microservice?

No. The pattern is about ownership, not hardware. A schema per service with its own login role on one Postgres server enforces the boundary for most systems, and separate databases or servers follow when services need different scaling, engines or failure isolation.

How do you join data across services?

Either compose at query time, calling each owning service and merging the results, or keep a read model: the service that needs the data subscribes to the owner's events and stores the fields it needs in its own tables, where a normal SQL join works.

How do you do reporting with a database per service?

Feed a separate reporting store, such as a warehouse or a read replica built for analytics, from each service's events or from change data capture. Reporting queries then never touch the services' production tables, and no service has to expose its schema to analysts.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders