MongoDB vs PostgreSQL: choose boundaries for a checkout workflow
Choose from the invariants the checkout must preserve. Either store can implement this workflow, but a bounded order snapshot, inventory contention, tenant constraints, notification handoff and adoption plan need explicit owners in both designs.
Decision guide for one tenant-scoped checkout workload, not a general NoSQL-versus-SQL ranking. MongoDB behavior refers to Server 8.x; PostgreSQL behavior refers to the selected supported server version and configured isolation. No performance benchmark is claimed. The scenario fixes catalog SKU-9 at revision 42 and 1,999 minor currency units when an order is accepted; the catalog later changes to 2,199. An order has at most 50 lines. Initial stock for tenant T-7 / SKU-9 is 3; a request reserves 2 with idempotency key R-1, retries R-1, attempts access as tenant T-8, a competing request tries to reserve 2, then notification fails after commit.
MongoDB and PostgreSQL are alternative primary stores for the same tenant-scoped checkout workload. The comparison holds the data facts and failure sequence constant so the choice turns on document versus relational boundaries, constraints, consistency and operational fit.
Compare the practical consequences
Scroll sideways to compare all columns on a smaller screen.
MongoDB and PostgreSQL by decision criterion
Criterion
MongoDB
PostgreSQL
What changes the decision
Order price snapshot
Store each accepted line's SKU, quantity, agreed unit price 1,999 minor units and catalog revision 42 in a bounded order document or normalized order_line rows.
Store the same agreed values in an order snapshot or order_line rows, separate from the mutable catalog price now 2,199.
Catalog changes never rewrite the accepted price. Enforce a maximum of 50 lines and preserve currency/unit metadata.
Tenant isolation
Derive T-7 from authenticated context and include it in every order/inventory predicate. Add tenant-aware unique keys where identifiers are tenant-local.
Derive T-7 from authenticated context, include it in joins and predicates, and use composite keys/row-level security only where their actual policy is tested.
A client request as T-8 must not read or mutate T-7 records in either design.
Single-item stock reservation
Use an atomic conditional update where available stock is at least 2; store bounded idempotency state with the same document or transact with a reservation record.
Use UPDATE ... WHERE available >= 2 and inspect affected rows; use a unique reservation key and transaction when a separate reservation row is required.
One request can reserve 2 from 3; same-key retry does not decrement again; competing requests cannot make stock negative.
Multi-record stock/order invariant
Embed the bounded state if reads/writes truly share one aggregate, otherwise use a replica-set/sharded-cluster transaction or a reservation/saga with reconciliation.
Use a transaction with row-level locking or conditional updates plus constraints; define lock order and retry behavior for conflicts.
Neither store makes arbitrary application work or external notifications part of the database transaction.
Uniqueness and validation
Use unique indexes and schema validation for expressible document constraints; cross-document rules remain explicit application/transaction logic.
Use unique, foreign-key, check and not-null constraints for relational rules where appropriate; complex workflow rules still need transaction logic.
Move invariants into the database where its constraint model can enforce them, and test every bypass path.
Notification failure after commit
Commit the order plus an outbox record in one transaction, then deliver asynchronously with idempotent event identity; a commit callback alone is not durable delivery.
Commit the order plus an outbox row in one SQL transaction, then publish asynchronously and mark delivery; consumer effects remain idempotent.
The order is committed while notification is pending/failed. Expose that state and retry delivery without creating another order.
Price revision and stale writes
Filter updates on expected catalog revision 42 and update atomically; reject a stale writer after catalog reaches revision 43 / 2,199.
Use a revision predicate in the UPDATE, or lock the catalog row within the transaction; check row count and reject stale writes.
The accepted order snapshot stays 1,999; a later edit based on revision 42 cannot overwrite revision 43 silently.
Migration and reversible adoption
Start with a narrow service boundary and dual-read/dual-write strategy owned by one migration coordinator; use change streams only with resume/reconciliation and retention limits.
Use expand/backfill/contract migrations and a transactional outbox or logical replication plan where needed; keep schema rollback and data rollback separate.
Cutover needs parity checks, idempotent backfill, a write freeze/dual-write policy and a tested route back. Application code alone cannot reverse divergent writes.
One tenant-scoped checkout accepts up to 50 order lines and must preserve the price accepted at catalog revision 42: SKU-9 costs 1,999 minor units at acceptance, then the catalog changes to 2,199. Stock starts at 3 and request R-1 reserves 2, retries, faces a cross-tenant attempt, a competing reservation and a notification failure after commit.
The fixed sequence exposes idempotency, stale-write, tenant and delivery boundaries in the same workflow. The expected state is one accepted order at 1,999, at most 1 remaining stock after R-1, no T-8 access, no negative stock and a notification that remains pending or failed after the business commit.
The outcome does not select a universal database. It forces each design to name the atomic unit, unique key, read-after-write promise and recovery owner.
Shared event trace · Worked example
SKU-9 is revision 42 at 1,999 minor units when the order is accepted. The order keeps that snapshot after the catalog changes to revision 43 at 2,199. R-1 reserves 2 of 3 units; retry R-1 must not reserve again. A competing request for 2 units is rejected. A T-8 attempt cannot touch T-7 data. After commit, failed notification remains retryable without creating another order.
Human-readable fixed scenario; no database was mutated. Every comparison row uses these same facts.
Non-executable fixed-workload trace; MongoDB/PostgreSQL transaction runtimes were not exercised.
Follow-up: What is the required final behavior after the notification failure?
Keep the committed order and its price snapshot, mark delivery pending/failed, and retry through a durable outbox with idempotent event identity. Do not reserve stock or create a second order again.
Should the order be a document or normalized rows?
A bounded order snapshot fits one MongoDB document when checkout and order reads operate on its lines together. PostgreSQL can store the same bounded snapshot in order and order_line rows with foreign keys and constraints. The stock balance remains independently contended in either design.
The 50-line limit makes the accepted-order snapshot bounded. MongoDB can embed those lines and atomically change one order document, but it does not turn a product update and order insert into one single-document write. PostgreSQL's order/order_line relations make joins and foreign keys direct, while transaction and index choices still govern the write.
Avoid a purely stylistic rule. Model access patterns, independent updates, aggregate growth and the cost of maintaining duplicated facts. Neither model should use the current catalog price to render a historical accepted order.
Data-shape trace · Worked example
MongoDB keeps at most 50 accepted line snapshots inside one order document, each retaining SKU-9, quantity, 1,999 minor units and revision 42. PostgreSQL stores the same bounded facts across an order row and its related line rows.
Human-readable model trace, not schema DDL or executable data. Neither description is a complete migration-ready schema.
Non-executable document/relation trace.
Follow-up: What if orders commonly contain thousands of lines?
Revisit the aggregate bound and page normalized or separately stored lines. A larger document or array is not a substitute for measuring size, update contention and the actual read path.
What stops two buyers from reserving the final units?
Both implementations need the condition and stock decrement at one atomic database boundary. MongoDB can conditionally update one inventory document; PostgreSQL can conditionally update one row and check the affected-row count.
For T-7 stock 3, R-1 requests 2. A second distinct key can reserve only the remaining 1. A competing request for 2 must match zero rows or be rejected; it cannot read 1 and later decrement to -1. Include tenant and SKU in the predicate.
If the reservation ledger is a separate record, persist the stock change and the unique operation key atomically. A unique key alone prevents duplicate ledger rows but does not prevent overselling; the conditional stock predicate alone does not make an external effect exactly once.
Atomic update trace · Worked example
Both stores apply the availability condition and decrement within one atomic single-record update. For T-7 and SKU-9, R-1 matches when 3 units are available and leaves 1. A second request for 2 matches no record and is rejected. A retry using R-1 resolves to its earlier result.
Human-readable outcome trace; it contains no database command and does not simulate competing clients.
Non-executable atomic-write trace; concurrency is not simulated.
Follow-up: Can a unique idempotency row replace the stock predicate?
No. It deduplicates one operation identity. The stock update still needs an atomic availability condition and the operation result must commit with the reservation record.
Treat the client's expected revision as a compare-and-set token. MongoDB includes revision 42 in the atomic update predicate. PostgreSQL can compare it in the UPDATE WHERE clause, or lock the row and then compare the still-current revision before writing. If the stored revision is already 43, return a conflict.
The accepted order stores 1,999 and revision 42 as a historical snapshot. The catalog's current value is a separate fact. A stale edit must not overwrite revision 43 merely because its client cached the old price.
A row lock alone does not reject a stale client: after waiting for another transaction, the lock holder may acquire the row at revision 43 and overwrite it unless it compares the client's expected revision under the lock. The accepted order still stores 1,999 and revision 42 as a historical snapshot; catalog current value is a separate fact.
Compare-and-set trace · Worked example
A writer loaded revision 42. Another writer has already changed SKU-9 to revision 43 at 2,199. The first writer's expected-revision condition no longer matches, so its edit is rejected. The order already accepted at 1,999 remains unchanged.
Human-readable stale-write outcome, not a database command. It does not claim a specific lock schedule.
Non-executable stale-write trace.
Follow-up: Should a rejected stale edit be retried automatically with revision 43?
Usually no. The user may be overwriting a meaningful change. Reload the latest record and require an explicit new decision, or use a business-specific merge rule.
Put tenant identity in every authorization predicate and key design. Use each database's native unique and validation constraints for invariants it can express, then retain application checks for workflow rules that span records.
MongoDB supports unique indexes and schema validation, but a cross-document stock/order rule still needs an atomic workflow. PostgreSQL can express foreign keys, checks and uniqueness across relational keys, while row-level security can add a defense layer when configured and tested.
Neither a document ID nor an index proves that the current caller belongs to the tenant. Bind the authenticated T-7 identity server-side and include it in read, write and delete filters. A T-8 request against T-7's SKU or order must fail without revealing existence if that is the API contract.
Authorization failure trace · Worked example
The authenticated principal belongs to T-7 but submits T-8. The service derives authority from the principal and constrains each order and inventory operation to T-7. The cross-tenant attempt reveals no record and changes no stock.
Human-readable authorization trace, not query or policy code. It does not configure database roles or application authentication.
Non-executable security trace.
Follow-up: Does PostgreSQL row-level security eliminate tenant predicates in code?
It can add database-enforced filtering when correctly enabled and scoped, but application query intent, connection role behavior and bypass paths still need tests. It does not remove authentication or authorization ownership.
When does checkout need a multi-record transaction?
Use a transaction if the order, inventory reservation and idempotency record must commit or abort together. MongoDB requires replica-set or sharded topology; PostgreSQL uses a transaction with an appropriate conflict/locking strategy. Keep notifications outside the transaction via an outbox.
A MongoDB standalone proof cannot validate multi-document transactions. A replica-set or sharded test should exercise transaction retry labels, duplicate operation keys and ambiguous commit recovery. PostgreSQL tests should cover concurrent reservations, constraints and serialization/deadlock retry behavior under the chosen isolation.
A transaction cannot atomically commit an email or external payment processor. Commit an outbox event with the order, then publish and mark delivery separately. If notification fails after checkout commit, the correct state is committed order plus retryable notification, not checkout rollback by fiction.
Transaction failure trace · Worked example
The database transaction commits the stock change, accepted order snapshot and outbox record together. A separate publisher sends the event. If the process crashes after sending but before recording delivery, it can send again; the consumer deduplicates by event identity.
Human-readable failure trace; no transaction or publisher code is supplied, and exactly-once delivery is not claimed.
Non-executable transaction/outbox trace; no topology execution.
Follow-up: What should an ambiguous commit response trigger?
Resolve the stable operation ID against durable order/reservation state before retrying. Do not assume the transaction failed merely because the client missed the response.
Build indexes from the same tenant/status/time feed query and verify representative plans. PostgreSQL and MongoDB both need a stable compound order and unique tie-breaker; neither index proves a production latency target.
For a descending feed by created_at and order ID, keyset pagination avoids large offsets and gives deterministic ties. In PostgreSQL inspect an analyzed plan with buffer details against safe representative data; in MongoDB inspect execution statistics. Compare rows/documents examined with results and account for index write cost.
Choose a consistency policy for the confirmation and feed. A secondary read in MongoDB can lag even after a majority write acknowledgement in MongoDB 8.0; PostgreSQL visibility depends on the transaction snapshot and replica routing. Route read-your-own-write paths according to the documented guarantee.
Shared query contract · Worked example
For both stores, the feed includes only accepted T-7 orders and orders them newest first with order ID as a unique tie-breaker. Each page continues after the last timestamp-and-ID pair. A representative explain plan is required before claiming index fit; this guide reports no plan or timing.
Human-readable query contract; no query or explain command was run.
Non-executable index and pagination trace.
Follow-up: Which database is faster for this feed?
The fixed facts contain no performance measurement. Benchmark both with the same representative data, workload, indexes, topology, durability and cache state before making a speed claim.
Move behind a narrow repository/service boundary, backfill with stable IDs and checkpoints, compare reads, then switch writes with an explicit dual-write or cutover policy. A rollback plan must reconcile writes made after cutover.
For MongoDB adoption from PostgreSQL, preserve a normalized source of truth during backfill and compare order counts, tenant ownership, price snapshots and stock totals. For PostgreSQL adoption from MongoDB, validate nested shape and bounded line counts before splitting documents into rows. Change streams or logical replication have their own retention, resume and reconciliation limits.
A reversible application flag is insufficient if writes diverge in both stores. Choose one write owner at each stage; define a short freeze, ordered dual-write with repair log, or transactional outbox bridge. Practice the return path with synthetic divergence before production cutover.
Cutover trace · Worked example
The migration team provisions the destination, records a stable source checkpoint, backfills in bounded idempotent batches, and compares tenant ownership, accepted prices/revisions, reservation keys and stock. It then gives writes to one owner and rehearses reconciliation and rollback before retiring the source.
Human-readable adoption trace; no datastore is connected and no backfill or production migration is performed.
Non-executable adoption plan; no production migration performed.
Follow-up: What makes the cutover measurable?
Compare stable business invariants and key ranges, not just total row/document counts: tenant ownership, accepted prices/revisions, reservation keys, nonnegative stock and notification states.
These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.
Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged MongoDB, rather than every job in the broader technology family.
Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged PostgreSQL, rather than every job in the broader technology family.
Middle-half salary ranges on one shared scale
The band runs from the 25th to 75th percentile; the vertical marker is the median. Both rows use approximate USD per year.
MongoDB $145,000 median
PostgreSQL $140,000 median
$100,000$170,000
How many source posts appear in both salary groups?
Source posts can appear in both groups in this salary dataset. The same advertised salary can therefore contribute to both summaries.
MongoDB posts in this dataset7 of 32 also tagged PostgreSQL · 21.9%
PostgreSQL posts in this dataset7 of 331 also tagged MongoDB · 2.1%
What these bars count
Bars count distinct source posts with known HN IDs in these salary cohorts, not every Hacker News post or the wider job market. Duplicate IDs count once; rows without a valid HN ID are left out, so the bars cannot establish overlap for the full population. These are source-post counts, not the salary-observation counts in the cards above. A missing tag does not prove a technology was not used. Overlap does not establish employer preference, adoption or a pay effect.