[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-en-transactional-outbox-postgres-zero-data-loss":3},{"id":4,"title":5,"author":6,"body":7,"cover":869,"description":870,"draft":871,"extension":872,"locale":873,"meta":874,"navigation":264,"path":875,"publishedAt":876,"seo":877,"seoTitle":878,"slug":879,"stem":880,"tags":881,"__hash__":885},"blog\u002Fen\u002Fblog\u002Ftransactional-outbox-postgres-zero-data-loss.md","Transactional outbox on Postgres: how not to lose an event when the server crashes","Manuel Tardivo",{"type":8,"value":9,"toc":858},"minimark",[10,24,29,32,35,38,41,45,51,54,58,123,138,142,343,346,350,363,398,706,716,720,732,735,749,752,756,759,779,782,786,798,801,804,808,842,845,854],[11,12,13,14,18,19,23],"p",{},"The ",[15,16,17],"strong",{},"transactional outbox pattern"," makes event emission (webhooks, notifications, queue messages) atomic with respect to the database: you write the event to an ",[20,21,22],"code",{},"outbox"," table in the same transaction as business data, and a worker publishes it afterward. It is one of the patterns we use at Snowinch when a system cannot afford to lose orders, payments, or state updates, even through crashes, restarts, or network timeouts.",[25,26,28],"h2",{"id":27},"the-problem-that-does-not-seem-to-exist-until-it-does","The problem that does not seem to exist until it does",[11,30,31],{},"You have an endpoint that receives an order. You save the order to the database, then send a message to the queue (or call a webhook, or publish an event). If the process crashes between the two operations, the order is saved but the event never left. No visible error, no automatic retry, just a silently lost event.",[11,33,34],{},"The opposite approach, emit the event before saving, has the same problem inverted: the event goes out but the save fails.",[11,36,37],{},"The critical point is that the two operations live on separate systems. The database has ACID transactions; the queue, broker, or external notification service does not participate in that transaction. There is no practical two-phase commit in this context, and even if there were you would not want to use it.",[11,39,40],{},"This is the pattern that shows up most often once a system grows past the prototype stage and starts handling data with real consequences.",[25,42,44],{"id":43},"the-solution-write-everything-to-the-database-publish-later","The solution: write everything to the database, publish later",[11,46,47,48,50],{},"The transactional outbox works like this: instead of emitting the event directly to the external system, you write it to an ",[20,49,22],{}," table in the same transaction as your business write. A separate worker reads the table and publishes events to the final destination.",[11,52,53],{},"Both operations become atomic with respect to the database, either both happen, or neither does. The worker can fail, time out, or restart: it picks up where it left off because unpublished events are still in the table.",[25,55,57],{"id":56},"minimal-schema","Minimal schema",[59,60,65],"pre",{"className":61,"code":62,"language":63,"meta":64,"style":64},"language-sql shiki shiki-themes github-light github-dark","CREATE TABLE outbox (\n  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n  created_at    timestamptz NOT NULL DEFAULT now(),\n  published_at  timestamptz,                  -- null = pending\n  topic         text NOT NULL,                -- e.g. 'order.created'\n  payload       jsonb NOT NULL,\n  attempts      int NOT NULL DEFAULT 0,\n  last_error    text\n);\n","sql","",[20,66,67,75,81,87,93,99,105,111,117],{"__ignoreMap":64},[68,69,72],"span",{"class":70,"line":71},"line",1,[68,73,74],{},"CREATE TABLE outbox (\n",[68,76,78],{"class":70,"line":77},2,[68,79,80],{},"  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n",[68,82,84],{"class":70,"line":83},3,[68,85,86],{},"  created_at    timestamptz NOT NULL DEFAULT now(),\n",[68,88,90],{"class":70,"line":89},4,[68,91,92],{},"  published_at  timestamptz,                  -- null = pending\n",[68,94,96],{"class":70,"line":95},5,[68,97,98],{},"  topic         text NOT NULL,                -- e.g. 'order.created'\n",[68,100,102],{"class":70,"line":101},6,[68,103,104],{},"  payload       jsonb NOT NULL,\n",[68,106,108],{"class":70,"line":107},7,[68,109,110],{},"  attempts      int NOT NULL DEFAULT 0,\n",[68,112,114],{"class":70,"line":113},8,[68,115,116],{},"  last_error    text\n",[68,118,120],{"class":70,"line":119},9,[68,121,122],{},");\n",[11,124,125,126,129,130,133,134,137],{},"A null ",[20,127,128],{},"published_at"," means the event is waiting. The worker sets it after confirmed publication. ",[20,131,132],{},"attempts"," and ",[20,135,136],{},"last_error"," support monitoring and backoff logic, they are not decorative.",[25,139,141],{"id":140},"write-inside-the-business-transaction","Write inside the business transaction",[59,143,147],{"className":144,"code":145,"language":146,"meta":64,"style":64},"language-typescript shiki shiki-themes github-light github-dark","\u002F\u002F Single transaction: both writes succeed or neither does\nawait db.transaction(async (trx) => {\n  const order = await trx('orders').insert({\n    user_id: userId,\n    total: orderTotal,\n    status: 'confirmed',\n  }).returning('*');\n\n  await trx('outbox').insert({\n    topic: 'order.created',\n    payload: {\n      order_id: order[0].id,\n      user_id: userId,\n      total: orderTotal,\n    },\n  });\n});\n","typescript",[20,148,149,155,191,224,229,234,245,260,266,284,295,301,313,319,325,331,337],{"__ignoreMap":64},[68,150,151],{"class":70,"line":71},[68,152,154],{"class":153},"sJ8bj","\u002F\u002F Single transaction: both writes succeed or neither does\n",[68,156,157,161,165,169,172,175,178,182,185,188],{"class":70,"line":77},[68,158,160],{"class":159},"szBVR","await",[68,162,164],{"class":163},"sVt8B"," db.",[68,166,168],{"class":167},"sScJk","transaction",[68,170,171],{"class":163},"(",[68,173,174],{"class":159},"async",[68,176,177],{"class":163}," (",[68,179,181],{"class":180},"s4XuR","trx",[68,183,184],{"class":163},") ",[68,186,187],{"class":159},"=>",[68,189,190],{"class":163}," {\n",[68,192,193,196,200,203,206,209,211,215,218,221],{"class":70,"line":83},[68,194,195],{"class":159},"  const",[68,197,199],{"class":198},"sj4cs"," order",[68,201,202],{"class":159}," =",[68,204,205],{"class":159}," await",[68,207,208],{"class":167}," trx",[68,210,171],{"class":163},[68,212,214],{"class":213},"sZZnC","'orders'",[68,216,217],{"class":163},").",[68,219,220],{"class":167},"insert",[68,222,223],{"class":163},"({\n",[68,225,226],{"class":70,"line":89},[68,227,228],{"class":163},"    user_id: userId,\n",[68,230,231],{"class":70,"line":95},[68,232,233],{"class":163},"    total: orderTotal,\n",[68,235,236,239,242],{"class":70,"line":101},[68,237,238],{"class":163},"    status: ",[68,240,241],{"class":213},"'confirmed'",[68,243,244],{"class":163},",\n",[68,246,247,250,253,255,258],{"class":70,"line":107},[68,248,249],{"class":163},"  }).",[68,251,252],{"class":167},"returning",[68,254,171],{"class":163},[68,256,257],{"class":213},"'*'",[68,259,122],{"class":163},[68,261,262],{"class":70,"line":113},[68,263,265],{"emptyLinePlaceholder":264},true,"\n",[68,267,268,271,273,275,278,280,282],{"class":70,"line":119},[68,269,270],{"class":159},"  await",[68,272,208],{"class":167},[68,274,171],{"class":163},[68,276,277],{"class":213},"'outbox'",[68,279,217],{"class":163},[68,281,220],{"class":167},[68,283,223],{"class":163},[68,285,287,290,293],{"class":70,"line":286},10,[68,288,289],{"class":163},"    topic: ",[68,291,292],{"class":213},"'order.created'",[68,294,244],{"class":163},[68,296,298],{"class":70,"line":297},11,[68,299,300],{"class":163},"    payload: {\n",[68,302,304,307,310],{"class":70,"line":303},12,[68,305,306],{"class":163},"      order_id: order[",[68,308,309],{"class":198},"0",[68,311,312],{"class":163},"].id,\n",[68,314,316],{"class":70,"line":315},13,[68,317,318],{"class":163},"      user_id: userId,\n",[68,320,322],{"class":70,"line":321},14,[68,323,324],{"class":163},"      total: orderTotal,\n",[68,326,328],{"class":70,"line":327},15,[68,329,330],{"class":163},"    },\n",[68,332,334],{"class":70,"line":333},16,[68,335,336],{"class":163},"  });\n",[68,338,340],{"class":70,"line":339},17,[68,341,342],{"class":163},"});\n",[11,344,345],{},"The external system, queue, webhook, notification, is not touched here. The transaction stays short and does not depend on any external service being available.",[25,347,349],{"id":348},"the-worker-skip-locked-for-safe-concurrency","The worker: SKIP LOCKED for safe concurrency",[11,351,352,353,362],{},"The worker must be idempotent and work correctly with multiple parallel instances. ",[354,355,359],"a",{"href":356,"rel":357},"https:\u002F\u002Fwww.postgresql.org\u002Fdocs\u002Fcurrent\u002Fsql-select.html#SQL-FOR-UPDATE-SHARE",[358],"nofollow",[20,360,361],{},"SKIP LOCKED"," is the Postgres primitive that lets multiple workers claim different rows without colliding or blocking each other.",[59,364,366],{"className":61,"code":365,"language":63,"meta":64,"style":64},"-- Claim up to 10 unpublished events, skipping rows already being processed\nSELECT * FROM outbox\nWHERE published_at IS NULL\nORDER BY created_at ASC\nFOR UPDATE SKIP LOCKED\nLIMIT 10;\n",[20,367,368,373,378,383,388,393],{"__ignoreMap":64},[68,369,370],{"class":70,"line":71},[68,371,372],{},"-- Claim up to 10 unpublished events, skipping rows already being processed\n",[68,374,375],{"class":70,"line":77},[68,376,377],{},"SELECT * FROM outbox\n",[68,379,380],{"class":70,"line":83},[68,381,382],{},"WHERE published_at IS NULL\n",[68,384,385],{"class":70,"line":89},[68,386,387],{},"ORDER BY created_at ASC\n",[68,389,390],{"class":70,"line":95},[68,391,392],{},"FOR UPDATE SKIP LOCKED\n",[68,394,395],{"class":70,"line":101},[68,396,397],{},"LIMIT 10;\n",[59,399,401],{"className":144,"code":400,"language":146,"meta":64,"style":64},"async function processOutbox() {\n  await db.transaction(async (trx) => {\n    const events = await trx.raw(`\n      SELECT * FROM outbox\n      WHERE published_at IS NULL\n      ORDER BY created_at ASC\n      FOR UPDATE SKIP LOCKED\n      LIMIT 10\n    `).then(r => r.rows);\n\n    for (const event of events) {\n      try {\n        await publishToExternalSystem(event.topic, event.payload);\n\n        await trx('outbox')\n          .where({ id: event.id })\n          .update({ published_at: new Date() });\n\n      } catch (err) {\n        \u002F\u002F Do not rethrow: event stays queued, worker continues\n        await trx('outbox')\n          .where({ id: event.id })\n          .update({\n            attempts: trx.raw('attempts + 1'),\n            last_error: String(err),\n          });\n      }\n    }\n  });\n}\n",[20,402,403,416,438,461,466,471,476,481,486,507,511,530,537,548,552,565,576,595,600,612,618,631,640,649,665,677,683,689,695,700],{"__ignoreMap":64},[68,404,405,407,410,413],{"class":70,"line":71},[68,406,174],{"class":159},[68,408,409],{"class":159}," function",[68,411,412],{"class":167}," processOutbox",[68,414,415],{"class":163},"() {\n",[68,417,418,420,422,424,426,428,430,432,434,436],{"class":70,"line":77},[68,419,270],{"class":159},[68,421,164],{"class":163},[68,423,168],{"class":167},[68,425,171],{"class":163},[68,427,174],{"class":159},[68,429,177],{"class":163},[68,431,181],{"class":180},[68,433,184],{"class":163},[68,435,187],{"class":159},[68,437,190],{"class":163},[68,439,440,443,446,448,450,453,456,458],{"class":70,"line":83},[68,441,442],{"class":159},"    const",[68,444,445],{"class":198}," events",[68,447,202],{"class":159},[68,449,205],{"class":159},[68,451,452],{"class":163}," trx.",[68,454,455],{"class":167},"raw",[68,457,171],{"class":163},[68,459,460],{"class":213},"`\n",[68,462,463],{"class":70,"line":89},[68,464,465],{"class":213},"      SELECT * FROM outbox\n",[68,467,468],{"class":70,"line":95},[68,469,470],{"class":213},"      WHERE published_at IS NULL\n",[68,472,473],{"class":70,"line":101},[68,474,475],{"class":213},"      ORDER BY created_at ASC\n",[68,477,478],{"class":70,"line":107},[68,479,480],{"class":213},"      FOR UPDATE SKIP LOCKED\n",[68,482,483],{"class":70,"line":113},[68,484,485],{"class":213},"      LIMIT 10\n",[68,487,488,491,493,496,498,501,504],{"class":70,"line":119},[68,489,490],{"class":213},"    `",[68,492,217],{"class":163},[68,494,495],{"class":167},"then",[68,497,171],{"class":163},[68,499,500],{"class":180},"r",[68,502,503],{"class":159}," =>",[68,505,506],{"class":163}," r.rows);\n",[68,508,509],{"class":70,"line":286},[68,510,265],{"emptyLinePlaceholder":264},[68,512,513,516,518,521,524,527],{"class":70,"line":297},[68,514,515],{"class":159},"    for",[68,517,177],{"class":163},[68,519,520],{"class":159},"const",[68,522,523],{"class":198}," event",[68,525,526],{"class":159}," of",[68,528,529],{"class":163}," events) {\n",[68,531,532,535],{"class":70,"line":303},[68,533,534],{"class":159},"      try",[68,536,190],{"class":163},[68,538,539,542,545],{"class":70,"line":315},[68,540,541],{"class":159},"        await",[68,543,544],{"class":167}," publishToExternalSystem",[68,546,547],{"class":163},"(event.topic, event.payload);\n",[68,549,550],{"class":70,"line":321},[68,551,265],{"emptyLinePlaceholder":264},[68,553,554,556,558,560,562],{"class":70,"line":327},[68,555,541],{"class":159},[68,557,208],{"class":167},[68,559,171],{"class":163},[68,561,277],{"class":213},[68,563,564],{"class":163},")\n",[68,566,567,570,573],{"class":70,"line":333},[68,568,569],{"class":163},"          .",[68,571,572],{"class":167},"where",[68,574,575],{"class":163},"({ id: event.id })\n",[68,577,578,580,583,586,589,592],{"class":70,"line":339},[68,579,569],{"class":163},[68,581,582],{"class":167},"update",[68,584,585],{"class":163},"({ published_at: ",[68,587,588],{"class":159},"new",[68,590,591],{"class":167}," Date",[68,593,594],{"class":163},"() });\n",[68,596,598],{"class":70,"line":597},18,[68,599,265],{"emptyLinePlaceholder":264},[68,601,603,606,609],{"class":70,"line":602},19,[68,604,605],{"class":163},"      } ",[68,607,608],{"class":159},"catch",[68,610,611],{"class":163}," (err) {\n",[68,613,615],{"class":70,"line":614},20,[68,616,617],{"class":153},"        \u002F\u002F Do not rethrow: event stays queued, worker continues\n",[68,619,621,623,625,627,629],{"class":70,"line":620},21,[68,622,541],{"class":159},[68,624,208],{"class":167},[68,626,171],{"class":163},[68,628,277],{"class":213},[68,630,564],{"class":163},[68,632,634,636,638],{"class":70,"line":633},22,[68,635,569],{"class":163},[68,637,572],{"class":167},[68,639,575],{"class":163},[68,641,643,645,647],{"class":70,"line":642},23,[68,644,569],{"class":163},[68,646,582],{"class":167},[68,648,223],{"class":163},[68,650,652,655,657,659,662],{"class":70,"line":651},24,[68,653,654],{"class":163},"            attempts: trx.",[68,656,455],{"class":167},[68,658,171],{"class":163},[68,660,661],{"class":213},"'attempts + 1'",[68,663,664],{"class":163},"),\n",[68,666,668,671,674],{"class":70,"line":667},25,[68,669,670],{"class":163},"            last_error: ",[68,672,673],{"class":167},"String",[68,675,676],{"class":163},"(err),\n",[68,678,680],{"class":70,"line":679},26,[68,681,682],{"class":163},"          });\n",[68,684,686],{"class":70,"line":685},27,[68,687,688],{"class":163},"      }\n",[68,690,692],{"class":70,"line":691},28,[68,693,694],{"class":163},"    }\n",[68,696,698],{"class":70,"line":697},29,[68,699,336],{"class":163},[68,701,703],{"class":70,"line":702},30,[68,704,705],{"class":163},"}\n",[11,707,708,709,712,713,715],{},"Important detail: ",[20,710,711],{},"FOR UPDATE SKIP LOCKED"," must live in the same transaction that updates ",[20,714,128],{},". If the worker transaction fails, the lock is released and the event remains available for the next cycle. Keep the external call as short as possible: you are holding a row lock until the destination responds.",[25,717,719],{"id":718},"frequency-and-backoff","Frequency and backoff",[11,721,722,723,726,727,731],{},"The worker runs on an interval, every 5 seconds, every 30, depending on acceptable latency for your system. It is not strictly a cron job: you can use a simple ",[20,724,725],{},"setInterval"," in a long-running Node process, or a scheduled job with the same logic described in the article on ",[354,728,730],{"href":729},"\u002Fen\u002Fblog\u002Fgithubcron-free-serverless-cron-jobs","serverless cron with GitHub Actions"," if you prefer not to keep a process always on.",[11,733,734],{},"For events with many failed attempts, add a backoff condition:",[59,736,738],{"className":61,"code":737,"language":63,"meta":64,"style":64},"WHERE published_at IS NULL\n  AND (attempts = 0 OR created_at \u003C now() - (attempts * interval '1 minute'))\n",[20,739,740,744],{"__ignoreMap":64},[68,741,742],{"class":70,"line":71},[68,743,382],{},[68,745,746],{"class":70,"line":77},[68,747,748],{},"  AND (attempts = 0 OR created_at \u003C now() - (attempts * interval '1 minute'))\n",[11,750,751],{},"This avoids hammering an event that keeps failing for a structural reason, a missing topic, malformed payload, or a permanently down external service.",[25,753,755],{"id":754},"cleanup","Cleanup",[11,757,758],{},"Published events can accumulate. A reasonable retention window, 7 days, 30 days, domain-dependent, and a periodic cleanup job:",[59,760,762],{"className":61,"code":761,"language":63,"meta":64,"style":64},"DELETE FROM outbox\nWHERE published_at IS NOT NULL\n  AND published_at \u003C now() - interval '30 days';\n",[20,763,764,769,774],{"__ignoreMap":64},[68,765,766],{"class":70,"line":71},[68,767,768],{},"DELETE FROM outbox\n",[68,770,771],{"class":70,"line":77},[68,772,773],{},"WHERE published_at IS NOT NULL\n",[68,775,776],{"class":70,"line":83},[68,777,778],{},"  AND published_at \u003C now() - interval '30 days';\n",[11,780,781],{},"Do not delete unpublished events on a time basis: if they are still there, there is a reason.",[25,783,785],{"id":784},"what-this-pattern-does-not-solve","What this pattern does not solve",[11,787,788,789,792,793,797],{},"The outbox guarantees ",[15,790,791],{},"at-least-once"," delivery, not exactly-once. The destination system must handle duplicates, or you must implement idempotency on the consumer side. On that topic, the article on ",[354,794,796],{"href":795},"\u002Fen\u002Fblog\u002Fstripe-webhook-idempotency-duplicates","Stripe webhooks and idempotency"," covers the consumer side in detail.",[11,799,800],{},"The pattern does not replace a dedicated queue (RabbitMQ, SQS, Kafka) for high volume or complex fan-out requirements. It is the right fit for systems that already use Postgres as the primary database and do not want extra infrastructure just to make events reliable, which covers most cases up to a certain volume.",[11,802,803],{},"It does not cover the case where the external system requires exactly-once delivery with no duplicates and does not support idempotency keys. That needs more sophisticated coordination.",[25,805,807],{"id":806},"operational-summary","Operational summary",[809,810,811,818,824,830,836,839],"ul",{},[812,813,814,815,817],"li",{},"Write the event to the ",[20,816,22],{}," table in the same transaction as business data, never as two separate operations.",[812,819,820,821,823],{},"Use ",[20,822,711],{}," in the worker for safe concurrency across multiple instances.",[812,825,826,827,829],{},"Set ",[20,828,128],{}," only after confirmed publication, inside the same transaction as the lock.",[812,831,832,833,835],{},"Handle failures with ",[20,834,132],{}," and backoff, do not rethrow exceptions that stall the worker.",[812,837,838],{},"Implement consumer idempotency: the outbox gives at-least-once, not exactly-once.",[812,840,841],{},"Add a cleanup job for published events, the table must not grow forever.",[11,843,844],{},"Tell us your context, constraints, and goals: we will say whether working together makes sense and how to set up a first step.",[11,846,847],{},[848,849,850,851],"email-link",{},"Email ",[852,853],"email-text",{},[855,856,857],"style",{},"html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sJ8bj, html code.shiki .sJ8bj{--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .szBVR, html code.shiki .szBVR{--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sVt8B, html code.shiki .sVt8B{--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sScJk, html code.shiki .sScJk{--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .s4XuR, html code.shiki .s4XuR{--shiki-default:#E36209;--shiki-dark:#FFAB70}html pre.shiki code .sj4cs, html code.shiki .sj4cs{--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .sZZnC, html code.shiki .sZZnC{--shiki-default:#032F62;--shiki-dark:#9ECBFF}",{"title":64,"searchDepth":77,"depth":77,"links":859},[860,861,862,863,864,865,866,867,868],{"id":27,"depth":77,"text":28},{"id":43,"depth":77,"text":44},{"id":56,"depth":77,"text":57},{"id":140,"depth":77,"text":141},{"id":348,"depth":77,"text":349},{"id":718,"depth":77,"text":719},{"id":754,"depth":77,"text":755},{"id":784,"depth":77,"text":785},{"id":806,"depth":77,"text":807},"\u002Fblog\u002F37_transactional_outbox_postgres_zero_data_loss_1x.webp","Transactional outbox on Postgres: write events with business data, publish with a SKIP LOCKED worker, at-least-once delivery and consumer idempotency.",false,"md","en",{},"\u002Fen\u002Fblog\u002Ftransactional-outbox-postgres-zero-data-loss","2026-06-19",{"title":5,"description":870},"Postgres outbox: no lost events on crash","transactional-outbox-postgres-zero-data-loss","en\u002Fblog\u002Ftransactional-outbox-postgres-zero-data-loss",[882,883,884],"postgres","mvp","automation","IiMIwHeE0Gumc0PBTUxsf8i3mwgYZAmPFEt-tnXjMrI"]