How do you design databases for microservices (schema-per-service) in SQL?
Topic: microservices, SQL Side. Level: Intermediate.
Answer
Give each service its own schema/database with isolated credentials; no service reads another's tables directly. This means you lose cross-service JOINs and foreign keys across boundaries — instead reference other aggregates by **id only**, and build read models via events (CQRS) when you need to display joined data. Each service migrates its own schema independently (Flyway/Liquibase).
```sql
-- order-service DB: reference customer by ID only, no FK to another service's table
CREATE TABLE orders (
id UUID PRIMARY KEY,
customer_id UUID NOT NULL, -- owned by customer-service; no cross-DB FK
total_cents BIGINT NOT NULL,
status TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
-- To show "orders with customer name", the order-service keeps a local
-- read model updated from customer-service events (no cross-service JOIN).
```