Engineering blueprint · PostgreSQL · Redis · Schema design

PostgreSQL Database Design for SaaS

A backend is only as reliable as its data model. I design PostgreSQL schemas that keep data correct at the database level, stay fast as tables grow and are easy to change safely.

Last reviewed

PostgreSQL Database Design for SaaS diagram

What the Architecture Covers

  • Schema modelling

    Normalized tables for tenants, products, orders and invoices, with foreign keys and check constraints that protect data integrity.

  • Multi-tenancy

    Tenant-scoped keys and filtering so every query is isolated per customer, without duplicating databases.

  • Indexing strategy

    Composite and partial indexes chosen from real query patterns and verified with EXPLAIN ANALYZE.

  • Query optimization

    Removing sequential scans, N+1 queries and heavy joins so hot endpoints stay in the low milliseconds.

  • Safe migrations

    Versioned, reversible migrations (Alembic or Django) that run automatically in the CI/CD pipeline.

  • Redis caching

    Redis for hot reads, rate limits and job queues, with explicit invalidation rules.

How the pieces fit

There are three layers: PostgreSQL as the single source of truth, a thin repository layer that owns every query, and Redis in front of the hottest reads. A typical request moves through them like this:

  1. 1Identify the tenant. Middleware resolves the tenant from the authenticated session or API key, never from a parameter the client controls.
  2. 2Scope every query. The repository layer (SQLAlchemy or the Django ORM) takes the tenant ID as a required argument, so a route handler cannot run an unscoped query by accident.
  3. 3Check the cache first. Hot reads look in Redis under a tenant-prefixed key. On a miss, the query goes to PostgreSQL and the result is cached with a TTL.
  4. 4Let the database reject bad data. Writes run in a transaction, and constraints refuse invalid rows even when application validation has a gap.
  5. 5Invalidate after commit. Once the transaction commits, the code deletes the cache keys it affected.
  6. 6Change the schema only through migrations. Alembic or Django migrations are reviewed like code and applied by the CI/CD pipeline before the new version takes traffic.

A multi-tenant schema with real constraints

I use one shared schema with a tenant_id column on every tenant-owned table, and I put tenant_id into the primary and foreign keys of child tables. That way the database itself guarantees an order line can never point at another tenant's product.

CREATE TABLE tenants (
    id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    slug      text NOT NULL UNIQUE,
    currency  char(3) NOT NULL DEFAULT 'USD'
);

CREATE TABLE products (
    tenant_id    bigint NOT NULL REFERENCES tenants (id),
    id           bigint GENERATED ALWAYS AS IDENTITY,
    sku          text NOT NULL,
    name         text NOT NULL,
    price_cents  integer NOT NULL CHECK (price_cents >= 0),
    archived_at  timestamptz,
    PRIMARY KEY (tenant_id, id),
    UNIQUE (tenant_id, sku)
);

CREATE TABLE orders (
    tenant_id    bigint NOT NULL REFERENCES tenants (id),
    id           bigint GENERATED ALWAYS AS IDENTITY,
    status       text NOT NULL DEFAULT 'pending'
                 CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')),
    total_cents  integer NOT NULL CHECK (total_cents >= 0),
    created_at   timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (tenant_id, id)
);

CREATE TABLE order_items (
    tenant_id   bigint NOT NULL,
    order_id    bigint NOT NULL,
    product_id  bigint NOT NULL,
    quantity    integer NOT NULL CHECK (quantity > 0),
    PRIMARY KEY (tenant_id, order_id, product_id),
    FOREIGN KEY (tenant_id, order_id) REFERENCES orders (tenant_id, id) ON DELETE CASCADE,
    FOREIGN KEY (tenant_id, product_id) REFERENCES products (tenant_id, id)
);

Money is stored as integer cents, statuses are limited by a check constraint, and SKUs are unique per tenant. PostgreSQL does not index foreign key columns automatically, so I add indexes where joins or cascading deletes need them.

Row-level security can enforce the same tenant filter inside the database as a second line of defence. One caveat: superusers, roles with BYPASSRLS and, by default, the table owner skip policies, so the application should connect as a separate non-owner role.

Indexes chosen from real queries

I index the queries the application actually runs, found through pg_stat_statements and the slow query log, not every column that might be filtered one day.

-- Composite: recent orders for a tenant in a given status
CREATE INDEX CONCURRENTLY orders_tenant_status_created_idx
    ON orders (tenant_id, status, created_at DESC);

-- Partial: catalog screens only list active products
CREATE INDEX CONCURRENTLY products_active_name_idx
    ON products (tenant_id, name)
    WHERE archived_at IS NULL;

-- Verify with the real query on realistic data volumes
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents, created_at
FROM orders
WHERE tenant_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;

Equality filters come first in the composite index, then the sort column. The partial index stays small because archived rows are left out, but the planner only uses it when the query's WHERE clause implies archived_at IS NULL.

In the plan I look for an Index Scan on the new index, no separate Sort node, estimated rows close to actual rows and mostly shared buffer hits. On a small table a sequential scan is often the right choice, so testing on realistic volumes matters. If estimates are far off, running ANALYZE to refresh statistics is the first fix. Remember that EXPLAIN ANALYZE really executes the statement, so wrap an UPDATE or DELETE in a transaction and roll it back.

Migrations that do not lock busy tables

Migrations set a short lock_timeout, so a blocked statement fails fast instead of queueing every other query behind it. CREATE INDEX CONCURRENTLY avoids blocking writes but cannot run inside a transaction block, so in Alembic it goes inside op.get_context().autocommit_block(). A failed concurrent build leaves an invalid index, which I drop before retrying.

Since PostgreSQL 11, adding a column with a constant default does not rewrite the table. When a required column needs values computed from existing data, I split the change across releases:

-- Release 1: nullable column (metadata only), plus code that writes it
ALTER TABLE orders ADD COLUMN currency char(3);

-- Once that code is live, backfill existing rows in batches
UPDATE orders o SET currency = t.currency
FROM tenants t
WHERE t.id = o.tenant_id AND o.currency IS NULL
  AND o.id BETWEEN 1 AND 50000;  -- repeat for each range

-- Release 2: enforce NOT NULL without a long exclusive lock
ALTER TABLE orders ADD CONSTRAINT orders_currency_not_null
    CHECK (currency IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_currency_not_null;
ALTER TABLE orders ALTER COLUMN currency SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT orders_currency_not_null;

The backfill starts only after the code that sets currency on new orders is live; otherwise fresh rows would keep arriving with nulls. VALIDATE CONSTRAINT scans the table without blocking writes, and from PostgreSQL 12 onward SET NOT NULL skips its own full scan when a valid check constraint already proves there are no nulls.

Redis cache-aside with explicit invalidation

Redis holds copies, never the only copy. Reads try the cache and fall back to PostgreSQL. Writes commit first, then delete the affected keys.

import json
import os
from contextlib import suppress

import redis

cache = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)
TTL_SECONDS = 300


def product_key(tenant_id: int, product_id: int) -> str:
    return f"t:{tenant_id}:product:{product_id}"


def get_product(session, tenant_id: int, product_id: int) -> dict | None:
    key = product_key(tenant_id, product_id)
    cached = None
    with suppress(redis.RedisError):  # a cache outage behaves like a miss
        cached = cache.get(key)
    if cached is not None:
        return json.loads(cached)
    product = products_repo.get(session, tenant_id, product_id)
    if product is not None:
        with suppress(redis.RedisError):
            cache.set(key, json.dumps(product), ex=TTL_SECONDS)
    return product


def update_product(session, tenant_id: int, product_id: int, changes: dict) -> None:
    products_repo.update(session, tenant_id, product_id, changes)
    session.commit()
    with suppress(redis.RedisError):  # only after a successful commit
        cache.delete(product_key(tenant_id, product_id))

Deleting after the commit stops a concurrent request from refilling the cache with the old row in between. A narrow race can still leave a stale entry, so the TTL limits how long it can live. The same database can also hold pgvector embeddings for search over company documents.

Failure modes and how the design handles them

  • A query forgets the tenant filter. Only the repository layer talks to the database, composite foreign keys block cross-tenant references, and a test with two tenants asserts neither can read the other's rows.
  • The cache serves stale data. Invalidation runs after every committed write, and the TTL heals a missed delete.
  • Redis is unavailable. Cache errors count as misses, so requests get slower instead of failing.
  • A migration blocks a hot table. lock_timeout makes it fail fast, risky changes run in steps and indexes are built concurrently.
  • Query plans degrade as data grows. pg_stat_statements shows which statements got slower, and EXPLAIN ANALYZE shows why.
  • Connections run out. Pool size times process count stays below max_connections, with PgBouncer or RDS Proxy added as traffic grows.
  • Data is lost. Automated backups with point-in-time recovery, covered in the AWS deployment architecture, plus a snapshot before risky migrations.

Checklist

  • Every tenant-owned table has a NOT NULL tenant_id, and child tables reference parents through (tenant_id, id).
  • Money is stored as integer cents or numeric, never as a float.
  • Each new index is justified by a real query and verified with EXPLAIN (ANALYZE, BUFFERS).
  • pg_stat_statements is enabled and reviewed regularly.
  • Migrations set lock_timeout, build indexes concurrently and add NOT NULL columns in steps.
  • Cache keys include the tenant ID, every key has a TTL and invalidation happens after commit.
  • A cross-tenant isolation test runs in CI.
  • Backups are restored on a schedule to prove they work.

Tools & Stack

  • PostgreSQL
  • Redis
  • SQLAlchemy
  • Alembic
  • Django ORM
  • pgvector

In Practice

Applied in the Mobileriz multi-marketplace backend: PostgreSQL models sellers, catalogs and orders, with Redis for caching, rate limits and jobs.

This blueprint is part of my Python backend & API development service. Tell me about your system on Upwork and I'll propose the right setup, timeline and cost.

Hire Me on Upwork