Polyglot Persistence: Pairing Relational SQL with Document Stores for Messaging Workloads
Not every workload shares the same access pattern. Relational databases (PostgreSQL) shine at strict foreign keys, multi-row ACID transactions, RLS permissions, and financial ledgers. Document databases (MongoDB) shine at append-heavy, semi-structured omnichannel message streams where WhatsApp interactive cards, Instagram story replies, and voice attachments evolve rapidly.
Matching Data Shapes to the Right Store
| Workload | Characteristics | Ideal Engine |
|---|---|---|
| Users, Workspaces, Roles, Billing | Strict relational integrity, ACID constraints, RLS | Relational SQL (PostgreSQL) |
| Omnichannel Messages & Attachments | High write volume, polymorphic channel payloads, time-ordered scans | Document Store (or JSONB partitioned tables) |
| Ephemeral Presence & Pub/Sub | Sub-millisecond fanout, TTL expiration | In-memory key-value / Pub/Sub (Redis/Valkey) |
| Full-Text & Vector Retrieval | Hybrid BM25 + HNSW semantic search | pgvector + FTS or dedicated search engine |
Designing Compound Indexes for Inbox Queries
In any messaging store, the hot query is almost always: "show the 50 most recent conversations in workspace X matching status Y, sorted by last message timestamp." Follow the Equality, Sort, Range (ESR) rule when designing compound indexes:
// ESR index pattern: equality fields first, sort field next, range filters last
const inboxListIndexSpec = {
workspaceId: 1,
status: 1,
lastMessageAt: -1,
} as const;
Avoiding Dual-Write Inconsistencies
When a single feature spans two datastores, assign one clear system of record per entity and avoid fragile synchronous dual-writes without recovery:
- Keep canonical identity and permissions in SQL.
- Reference entities across stores by immutable UUIDs rather than mutable emails or slugs.
- Use durable workflows or transactional outbox events whenever a state change in Store A must reliably project into Store B.
Next: protect third-party API keys and OAuth access tokens stored in your database in Secret Management and Envelope Encryption.