Keep PostgreSQL authoritative while Elasticsearch handles search across 100 million records. A practical design for CDC, replay-safe deletes, freshness, and rebuilds.
Keep PostgreSQL authoritative while Elasticsearch handles search across 100 million records. A practical design for CDC, replay-safe deletes, freshness, and rebuilds.
Search architecture at 100 million records starts with a clear rule: PostgreSQL owns the data, and Elasticsearch serves a rebuildable search index. The difficult part is defining what happens between a database commit and a searchable result.
Consider a fictional multi-tenant catalog. PostgreSQL owns product records, publication status, and permissions. Users need text search, filters, and relevance ranking. A separate search engine looks attractive, but writing to two systems creates a new correctness problem before it solves a capacity problem.
I would start by defining what “without losing consistency” means. PostgreSQL transactions remain authoritative. Search converges to their state through a durable, recoverable pipeline. Search results can lag, and that lag must be visible in the product contract. The architecture does not turn Elasticsearch into a linearizable view of every committed PostgreSQL transaction.
For this catalog, the contract is:
Search freshness is separate. A target such as “normally searchable within five seconds” is a hypothetical service objective to measure, not a property established by this diagram. During a search outage, database writes may continue while search becomes stale. The product must decide whether to show that state, provide a narrower fallback, or reject search requests.
The ordering guarantee is per document. A PostgreSQL transaction updating several records can become visible in search through several indexing operations. This design does not provide an atomic search snapshot of that whole database transaction.
A hundred million records does not automatically require Elasticsearch. PostgreSQL has full-text search, relational predicates, and indexes. Its full-text-search documentation describes GIN as the preferred text-search index type.
A stored search vector with a GIN index, or a matching expression index, is a practical starting point. Keep the text-search configuration consistent between indexing and querying, and handle nullable fields explicitly. The table-and-index examples cover these choices.
Start with representative query shapes: text plus tenant, visibility status, category, and the required sort. Measure realistic term frequencies, tenant sizes, concurrent reads, and update activity. Inspect query plans and index maintenance costs. A selective tenant predicate and a narrow search requirement may produce a different answer from broad cross-catalog relevance queries.
A dedicated engine becomes useful when measured requirements justify independent search scaling, richer relevance behavior, or a search workload that interferes with the transactional workload. It also introduces synchronization, another failure domain, and index rebuild operations. Include those costs in the comparison.
For the remaining design, assume a hypothetical 100 million live documents, averaging 2 KB of projected JSON, 300 mutations per second at peak, and 2,000 search requests per second. The payload alone is approximately 200 GB in decimal units. These are planning inputs, not a benchmark. Actual index storage, query capacity, and useful shard sizes require measurements on the intended mappings and workload.
The naive request handler updates PostgreSQL and then indexes the document. If it crashes after the commit but before indexing, search misses the update. Reversing the order allows search to expose a change that never committed. Retrying the HTTP request does not close either gap reliably.
Two common bridges are change data capture, or CDC, from the database’s committed change log, and a transactional outbox written alongside application data. They can be combined: our worked design inserts a full search-document snapshot into an outbox in the same transaction as the source mutation, then captures that outbox through CDC.
The outbox event contains the stable document ID, tenant, source revision, deletion flag, and complete projected content. A committed transaction contains both the source change and its event; a rolled-back transaction contains neither. A direct table-CDC design can also work, but constructing documents from related tables requires an equally explicit consistency and versioning strategy.
Distinguish event identity from document order. An event UUID can identify an exact delivery, while the document revision orders all changes to that record. Keying a durable stream by aggregate identity helps preserve local ordering; the projection must still tolerate replay. The Debezium outbox router describes event and aggregate keys.
Assume at-least-once delivery. Capture can resume from an earlier checkpoint and redeliver events. The PostgreSQL logical-decoding documentation discusses replay after a crash. The indexing consumer therefore needs idempotent handling, rather than an assumption that each event arrives exactly once.
Checkpoint capture only after events reach durable storage. Checkpoint application only after the corresponding indexing outcomes are handled. These are different positions: an event safely captured in a log may still be waiting to reach search.
Use a stable identity, such as tenant plus record ID, and a monotonically increasing source revision. PostgreSQL serializes updates for that aggregate, for example by locking its revision-bearing row and incrementing the revision inside the mutation transaction. Every writer follows this path.
The projection has one logical owner and one version contract for that identity. Multiple workers may process different partitions, but they must not invent independent revision counters. Timestamps are poor replacements: clocks can disagree, and multiple changes can share a timestamp.
Every change affecting the search document must advance its revision. If a category rename changes thousands of denormalized documents, that dependency needs a fan-out update strategy. Merely versioning changes to the primary product row leaves category-derived fields stale.
Keep each revision’s payload immutable and self-contained. Skipping revision 42 after revision 43 is safe when 43 contains the complete replacement document. It can lose information when events contain independent patches. If a consumer instead rereads PostgreSQL, publish the revision of the state actually read, not an old event revision attached to newer content.
The Elasticsearch index API supports strict external versioning. With version_type=external, an incoming version must be greater than the indexed version. Equal or lower versions produce a conflict. Use the index operation for complete replacements, carrying the source revision as the external version.
Classify the specific version conflict as an already-applied or superseded event only under the immutable revision-to-payload contract. An equal revision reused for different content is a source bug. Do not switch to external_gte merely to silence duplicate conflicts: accepting equal versions weakens that protection.
Keep this rule across schema changes too. Reinterpreting one retained event as two different payloads under the same document revision makes equal-version conflicts ambiguous. Version the projection schema, make replay transformations deterministic, and rebuild a new generation deliberately when the representation changes.
Suppose revision 41 describes a blue mug, revision 42 changes its title, and revision 43 deletes it. If 42 arrives after 43, the final search state must remain deleted.
Physically deleting the Elasticsearch document is insufficient protection against arbitrarily delayed events. The delete API documentation explains that deleted-version information is retained only for a limited period controlled by index.gc_deletes. An old update arriving after that protection expires can recreate a document.
Instead, index a small replacement at revision 43 containing the identity, tenant, and deleted: true. Exclude tombstones through the search query. The document and its version remain present, so revision 42 is rejected. A legitimate recreation can use revision 44.
Preserve this revision lineage in PostgreSQL too, using retained logical-delete records or a durable identity registry. Hard deletion followed by resetting an ID to revision 1 breaks the contract. Backfills and rebuilds must carry tombstones and their revisions. This design retains tombstones for the identity’s lifetime; purging them requires a separate proof that no old producer, replay, or backfill can address that identity again.
An outbox cleanup delete is different from a business deletion. Removing a delivered outbox row must not remove its product from search. Likewise, a Kafka null tombstone is not the persistent Elasticsearch document described here. Emit a versioned business-delete event with an explicit payload.
The following standard-library example models the greater-than check and retained tombstones. Save it as projection_example.py and run python3 projection_example.py.
def project(index, event):
revision = event["revision"]
if type(revision) is not int or not 0 < revision <= 2**63 - 1:
raise ValueError("Revision must be a positive signed 64-bit integer")
if type(event["deleted"]) is not bool:
raise ValueError("deleted must be a boolean")
previous = index.get(event["id"])
if previous is not None and revision <= previous["revision"]:
return False
index[event["id"]] = dict(event)
return True
if __name__ == "__main__":
# Full immutable snapshots from one hypothetical source revision lineage.
index = {}
for event in (
{"id": "tenant-a:P42", "revision": 41, "deleted": False, "title": "Blue mug"},
{"id": "tenant-a:P42", "revision": 43, "deleted": True},
{"id": "tenant-a:P42", "revision": 42, "deleted": False, "title": "Red mug"},
{"id": "tenant-a:P42", "revision": 44, "deleted": False, "title": "Green mug"},
):
accepted = project(index, event)
current = index[event["id"]]
print(event["revision"], accepted, current["revision"], current["deleted"])The delayed revision 42 is rejected while revision 43 remains deleted. Revision 44 is accepted as a recreation. Equal deliveries are rejected too. This is a small ordering model, not an Elasticsearch client, concurrency test, or throughput measurement. It assumes immutable full snapshots from the source.
A PostgreSQL commit confirms the authoritative mutation. A successful Elasticsearch indexing response confirms a different step. Search visibility follows a refresh. The refresh documentation distinguishes these operations and explains refresh=wait_for.
Durability is another distinction. Elasticsearch translog acknowledgment depends on its durability settings. A refresh makes changes searchable; it is not the same operation as making a write durable. Neither mechanism creates a distributed transaction with PostgreSQL.
For immediate read-your-writes behavior, return the committed record or read it directly from PostgreSQL. If the product requires a search-specific acknowledgment, return an operation token and wait, with a deadline, until the projection has applied at least that revision and the relevant change is searchable. Handle timeout explicitly.
Calling refresh=wait_for on an indexing request cannot make a queued CDC event arrive sooner. Forcing refreshes indiscriminately also adds indexing work. Reserve stronger visibility handling for interactions that need it.
Search can return candidate IDs that the application hydrates from current PostgreSQL rows. This removes deleted candidates and supplies current record data. It also supports authoritative permission checks. Preserve the search ordering among accepted candidates rather than accidentally replacing relevance with database retrieval order.
Use the PostgreSQL primary or a read path with the required freshness guarantee for these checks. An ordinary asynchronous replica may still lag a deletion or permission revocation. These authoritative checks do not make the ranked search page, or all queries used to assemble it, one consistent PostgreSQL snapshot.
Hydration does not repair missing recall: a newly committed matching record absent from the index was never a candidate. It does not make index counts, facets, or ranking current. Filtering stale candidates can also produce short pages. Decide whether to overfetch, return fewer results, or expose a bounded continuation process.
Apply a trusted tenant restriction before candidate retrieval, and recheck current fine-grained permissions before returning protected content. Stale indexed ACLs must not authorize access. Raw search counts or facets can reveal information about rejected candidates, so omit them or compute them through a permission-correct path when that matters. If authoritative authorization is unavailable, fail closed for protected records.
Project only fields search needs. Use deliberate mappings for text, identifiers, status, filters, and sorting. Unbounded dynamic fields and indexing unnecessary content increase storage and operational uncertainty.
An inverted index maps terms to postings, lists of documents containing those terms. Search combines these lists with filters to find candidates, rather than scanning every JSON document. That explains why document count alone is an incomplete capacity measure. Common terms can still produce large candidate sets. Ranking, sorting, and facets require additional work over matches, and their cost depends on the query. Benchmark representative broad queries alongside selective ones.
Include authoritative hydration in the read budget. At our hypothetical 2,000 searches per second and 20 candidate records per search, PostgreSQL receives 40,000 candidate IDs per second. That is not 40,000 SQL queries: fetch candidates and check access in a bounded batch per search, using tenant and IDs with an appropriate index. Overfetch increases this work. Measure batch latency at p95 under concurrent load, then budget in-flight batches and connection-pool capacity alongside transactional traffic. Elasticsearch scaling does not remove this PostgreSQL dependency.
Measure primary index size on representative documents, then account for replicas, segment merges, retained tombstones, and recovery headroom. A rebuild temporarily adds another generation. Keeping both generations current during a rollback window also adds write work. The source JSON size alone cannot predict this footprint.
For a hypothetical sizing exercise, if a representative measurement projects 400 GB of primary index storage at the target corpus size, one replica makes that approximately 800 GB. Keeping equally sized old and new generations during a rebuild makes it approximately 1.6 TB before merge, recovery, backlog, and other headroom. These decimal-unit calculations illustrate the budget, not measured capacity or a universal multiplier. Choose additional space and shard counts through real query, indexing, and failure-recovery tests.
Batch indexing by both document count and bytes, with bounded requests in flight. Measure sustained throughput while search traffic and merges are active. Refresh frequency, replicas, payload size, and update frequency all affect the result. The indexing-performance guide recommends testing bulk request sizes and handling overload signals.
Choose shard count from measured shard sizes, recovery time, and query concurrency. More shards create more coordination and resource overhead; they are not free parallelism. The shard-sizing guide treats this as a workload-dependent decision.
Tenant routing may reduce scatter across shards, but a large or busy tenant can create a hotspot. Routing is not an authorization boundary. Keep the same routing value for every live write, tombstone, read, and backfill of an identity. A changed route can target a different shard and undermine the intended per-document version protection.
Limit expensive query shapes, such as unbounded aggregations or broadly matching wildcard searches. For deep pagination, use a point in time, or PIT, with search_after and an appropriate stable tie-breaker, following the pagination documentation. A PIT stabilizes its search view; current PostgreSQL authorization checks can still remove candidates between pages.
Keep the query and sort unchanged, carry the full last-hit sort tuple including the PIT tie-breaker, and use the latest returned PIT ID. Expiry requires a new search session. A PIT preserves the index view that was visible when opened, not a PostgreSQL snapshot or an atomically applied CDC transaction. Long-lived PITs also retain resources.
A mapping change or index repair should not require stopping writes and hoping a second copy catches up. Build generation B while generation A continues serving search.
The critical boundary is a consistent source snapshot tied to a known CDC position. PostgreSQL can export a snapshot when creating a logical replication slot; that snapshot represents the database state before the changes in the stream. See its exported-snapshot documentation. A wall-clock timestamp or “start CDC after the scan” is not an equivalent boundary.
Prefer the connector’s supported snapshot protocol. In a lower-level implementation, backfill readers must import the exported snapshot into repeatable-read transactions before their first query. The replication protocol specifies that the exported snapshot is valid only until the next command on the exporting replication connection or its closure. Coordinate all reader imports before advancing that connection. Record both the snapshot identity and the returned consistent stream position; an unrelated database scan cannot substitute for this linkage.
The rebuild then follows these steps:
During this process, the projection service feeds both generations from the same immutable event stream, tracking their checkpoints independently. Keep A current during the rollback window. Retaining an old index without continuing its updates does not make it a safe immediate rollback target.
A high-water mark is a set of positions when the transport has multiple partitions. One advanced partition does not prove that every document is caught up. Account for failed and in-flight bulk items in each generation before declaring the barrier complete. A source capture position alone says nothing about search visibility.
Elasticsearch alias operations can make the remove-and-add switch atomic. Validate the expected alias state, use must_exist: true where partial success is inappropriate, and inspect action results because validation failures can allow some actions to succeed. Verify the resulting alias. Alias atomicity does not freeze PostgreSQL writes or replace CDC catch-up.
Existing PIT readers may retain the earlier search view. Keep the old generation long enough for those readers and the rollback policy. Budget the long source snapshot’s impact on PostgreSQL cleanup, and monitor retained WAL during capture.
Track source-to-capture lag, capture-to-index lag, indexing errors, search visibility, and oldest unprocessed event age separately. A healthy consumer process can still be falling behind.
Capacity must exceed incoming traffic during recovery. With hypothetical arrival and processing rates of 300 and 900 events per second, a 270,000-event backlog takes about 450 seconds to drain: 270,000 / (900 - 300). This assumes stable rates and no new bottleneck. It is planning arithmetic, not a measured recovery time.
Inspect every item in a bulk response. Some operations can succeed while others fail. Retry transient failures with backoff and backpressure; isolate invalid mappings or malformed payloads for repair. Do not silently mark a whole batch complete because its HTTP request returned successfully. The bulk API describes per-item outcomes.
A poison event needs a visible repair state and retained source information. Skipping it indefinitely breaks convergence. Checkpoint advancement must reflect an explicit recovery policy, including how that document will be repaired.
Retention bounds the recovery promise. Replication slots can retain substantial WAL, and configured WAL limits can leave a lagging slot without required history. Monitor storage and slot validity. If history is lost, rebuild from a new consistent cut instead of assuming replay remains complete.
Run reconciliation independently of event delivery. Compare source and projection IDs, revisions, and deletion flags in stable ranges, then investigate mismatches. Counts alone can match while the wrong records are indexed. If comparing hashes, define one canonical projection representation; do not compare unrelated database and index serialization.
Repair from authoritative current state and its revision, using the same replacement rule as normal delivery. Route repair writes through the projection owner. An operational script using an unversioned index request can undo the ordering guarantees established everywhere else.
Finally, constrain fallback behavior. Redirecting every search request to an untested PostgreSQL query during an outage can overload the source database. A useful fallback may offer only exact-ID lookup or a bounded, indexed tenant query. Return an explicit incomplete or unavailable state when neither search path can meet its contract.
A recoverable search architecture keeps PostgreSQL authoritative, makes publication durable, rejects stale revisions, retains delete lineage, and supports rehearsed rebuilds. The record count helps size the work; the correctness contract determines whether the result can be trusted.
For the messaging trade-offs behind the bridge, see Kafka vs RabbitMQ: When to Choose Each.
Scala, JVM, AI, and backend systems. I send practical articles when there is something worth reading.
Join the newsletterNecessary cookies keep the site working. With your permission, I use analytics cookies to understand which articles are useful.