Consumer idempotent و الگوی Inbox
"Consequently, a consumer must be idempotent: the outcome of processing the same message repeatedly must be the same as processing the message once." — Chris Richardson، Pattern: Idempotent Consumer، microservices.io
خلاصه (Summary): brokerی که هیچ پیامی را گم نمیکند حاضر است همان پیام را دو بار تحویل بدهد؛ پس consumer باید تحویل دوم را بیاثر کند: یک کلید پایدار، یک unique constraint، و ثبت کلید در همان transaction اثر جانبی. تمرکز (Focus): کلید idempotency (Idempotency Key) و اینکه هر broker از کجا یکی به شما میدهد، جدول inbox، «اول process بعد mark» در برابر «اول mark بعد process»، تکراریهای همزمان، TTL و پاکسازی، idempotency طبیعی، اثرهای جانبی غیرتراکنشی، projectionهای idempotent و تست. هدف یادگیری (Learning goal): هر consumer از نوع at-least-once را به consumer «عملاً یکبار» تبدیل کنید، کلید را انتخاب کنید، جدول dedup را اندازه و منقضی کنید، و بدانید inbox کدام اثرها را میپوشاند و کدام را نه.
این صفحه مرجع کامل حذف تکراریها در سمت consumer است: کلید idempotency و منبعش در RabbitMQ، Kafka، Redis Streams، NATS JetStream، Pulsar، SQS و Azure Service Bus؛ جدول inbox (processed_messages) و الگوی تراکنشی دور آن؛ دو ترتیب mark و process؛ race میان تکراریهای همزمان؛ TTL و اندازهگیری؛ idempotency طبیعی با upsert و update شرطی؛ اثرهایی که در transaction دیتابیس جا نمیشوند (ایمیل، HTTP)؛ projectionهای idempotent با version check؛ همتای HTTP یعنی Idempotency-Key؛ و تست همهٔ اینها. همسایهها را عمداً دوباره درس نمیدهیم: اینکه چرا اصلاً تکراری میرسد (استدلال دو ژنرال، idempotent producer و transactionهای Kafka در سمت broker) در تضمینهای تحویل است؛ سازوکار ack و offset و XACK در تأیید پیام؛ نیمهٔ دیگر این جفت در Transactional Outbox؛ ترتیب میان partitionها در ترتیب و Partitioning؛ dead-letter کردن در Dead-Letter Queue؛ و سمت دیتابیس (unique index و transaction) در ACID و Transaction.
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| پنج راه idempotency در یک جدول | همهچیز در یک دقیقه |
| چرا consumer تکراری میگیرد و چرا broker نمیتواند درستش کند | چرا consumerها باید idempotent باشند |
| ایده از کجا آمده (EIP، Richardson، Stripe، مستندات طراحی Kafka) | ایده از کجا آمده |
| idempotent در برابر «safe» و «exactly-once» | Idempotency و تحویل تکراری |
| روی کدام شناسه dedup کنیم (message id، offset، entry id، business key) | کلید idempotency |
| جدول، schemaاش و معنای دوم «inbox» | جدول inbox |
| transaction: بررسی + اثر + mark در یک commit | الگوی تراکنشی |
| mark-then-process در برابر process-then-mark با timeline | ترتیب mark |
| دو worker، یک پیام، یک لحظه | تکراریهای همزمان |
upsert، SET بهجای +1، update شرطی | Idempotency طبیعی |
| ایمیل، HTTP، فراخوانی پرداخت | اثرهای جانبی غیرتراکنشی |
| TTL، پنجرهٔ dedup، پاکسازی، حذف partition، اندازهگیری | TTL، پنجره و پاکسازی |
| read model، version check، رویداد خارج از ترتیب | Projectionهای idempotent |
| ذخیرهٔ offset کنار خروجی | Offset کنار خروجی |
| همتای HTTP | Idempotency-Key در لبهٔ HTTP |
| تنظیمات، کدهای خطا، primitive هر store | سازوکار |
| جدول مسئله به راهحل | راهحل مسئلههای کلاسیک |
| کدام خطا را retry کنیم | Retry و مدیریت خطا |
| کدام تکنیک برای کدام بار کاری | انتخاب رویکرد |
| کد Go (pgx) و Laravel | Go، Laravel |
| جزئیات RabbitMQ، Kafka، Redis Streams | تفاوتهای اجرا در brokerها |
| از monolith تا چندمنطقهای | در معماری |
| بازتولید تکراریها و دیدن ردشدنشان در inbox | آزمایشگاه |
| باورهای غلط، چکیده، تعریف همهٔ اصطلاحها | بدفهمیها، چکیده، واژهنامه |
همهچیز در یک دقیقه
پنج راه برای ایمنکردن consumer در برابر تکراری. هر سطر پایینتر باز میشود.
| تکنیک | به زبان ساده | چه چیزی لازم دارد | چه چیزی را میپوشاند | چه چیزی را نمیپوشاند |
|---|---|---|---|---|
| Idempotency طبیعی (Natural idempotency) | عملیات هر چندبار اجرا شود نتیجه یکی است (SET status = 'paid'، upsert با key) | چیز اضافهای نمیخواهد | بهروزرسانی با key، projection، refresh کش | increment، append، «ایمیل بفرست» |
| جدول inbox (Idempotent consumer) | هر شناسهای را که تمام کردهاید به یاد بسپارید؛ دومی را رد کنید | کلید یکتا برای هر پیام، یک دیتابیس | هر چیزی که در همان transaction دیتابیس نوشته شود | اثر در سیستمهای دیگر |
| Version check | رویداد را فقط وقتی اعمال کن که versionاش از version ذخیرهشده بیشتر باشد | version هر aggregate در پیام | تکراری و خارج از ترتیب در read model | commandهای بدون version |
| کلید idempotency پاییندستی (Downstream key) | شناسهٔ پیام را به سیستمی که صدا میزنید بدهید؛ خودش dedup میکند | سیستم پاییندستی که کلید را بپذیرد | فراخوانی HTTP، پرداخت، APIهای provider | providerهایی که کلید را نادیده میگیرند (بیشتر APIهای ایمیل) |
| پنجرهٔ dedup سمت broker | broker سمت producer شناسهٔ تکراری را در یک پنجره دور میاندازد | شناسهای که producer انتخاب کند | retry producer در همان پنجره | redelivery سمت consumer؛ هر چه بعد از پنجره بیاید |
ترتیب «mark» و «process».
| ترتیب | crash میان دو قدم | semantics واقعی تحویل |
|---|---|---|
| اول process، بعد mark (دو commit) | اثر انجام شده، mark نیست: تحویل بعدی اثر را تکرار میکند | At-least-once (همان باگ اصلی، یک قدم دیرتر) |
| اول mark، بعد process (دو commit) | mark هست، اثر نیست: تحویل بعدی رد میشود، کار گم میشود | At-most-once |
| mark و process در یک transaction | هر دو با هم rollback میشوند | Effectively-once، اگر اثر در همان دیتابیس باشد |
هر broker کلید را از کجا میدهد.
| Broker | شناسهٔ انتخابشده توسط producer | شناسهٔ ساختهشده توسط broker | پایدار در redelivery | پایدار در retry producer |
|---|---|---|---|---|
| RabbitMQ | property به نام message-id (اختیاری، هرگز چک نمیشود) | ندارد (delivery tag مخصوص هر channel است) | بله (message-id بعد از requeue میماند) | بله، اگر producer همان را دوباره بدهد |
| Kafka | header یا فیلد payload | topic-partition-offset | بله | offset: نه (دو offset). header: بله |
| Redis Streams | فیلدی مثل event_id؛ یا IDMP با pid + iid (نسخهٔ 8.6 به بعد) | entry id به شکل ms-seq | بله (بعد از XCLAIM/XAUTOCLAIM همان id) | entry id: نه. IDMP: بله |
| صف Laravel | property دلخواه خودتان به نام $messageId | uuid داخل payload ($this->job->uuid()) | بله | uuid: نه (dispatch تازه، uuid تازه) |
چرا consumerها باید idempotent باشند
consumer دو کار میکند: اثر را انجام میدهد، و بعد به broker خبر میدهد که تمام شد (ack، commit کردن offset، XACK). خرابی میان این دو broker را در تردید میگذارد، و brokerِ at-least-once تردید را با تحویل دوباره حل میکند. تکراری از جاهای دیگر هم میآید: producerی که بعد از گمشدن confirm دوباره فرستاده، consumerی که وسط کار در rebalance partition را از دست داده ولی هنوز کار میکند، visibility timeout (در SQS)، retry_after (در Laravel)، یا pending entry بیکاری که consumer دیگری claim میکند (در Redis). تضمینهای تحویل توضیح میدهد چرا هیچ پروتکلی این را از بین نمیبرد. نتیجه اینجا به شما میرسد: تحویل دوم باید بیضرر باشد.
| ارزانتر، ضعیفتر | گرانتر، قویتر |
|---|---|
| dedup نکنیم و تکراری نادر را تحمل کنیم (یک خط log، یک refresh کش) | جدول inbox با unique key در transaction کسبوکاری |
| dedup روی شناسهٔ دمدست (offset) | dedup روی business key که producer انتخاب کرده (تکراریهای سمت producer را هم میگیرد) |
| TTL کوتاه، جدول کوچک | پنجرهٔ بلند، جدول بزرگ، replayها امن |
SET NX در Redis بهعنوان store تکرارییاب (سریع، سیستم جدا) | unique constraint در همان دیتابیس (atomic با اثر) |
تصویری از زندگی روزمره. رختآویز یک سالن. کت را میدهید و بلیط شمارهدار میگیرید. اگر مسئول مطمئن نباشد که کت را بردهاید و دوباره به شما تعارف کند، شمارهٔ بلیط نشان میدهد کت رفته است. بلیط همان لحظهای نوشته میشود که کت دستبهدست میشود: نه قبل، نه بعد. این همان transaction است. رختآویزی که بلیطها را در دفتر جداگانهای و دیرتر ثبت کند همان طراحی «اول process، بعد mark» است و گاهی یک کت را دو بار تحویل میدهد.
سه بدفهمی رایج، همین ابتدا
- «broker ما exactly-once است، پس به این نیازی ندارم.» idempotent producer و transactionهای Kafka تکراریهای سمت broker و جریان Kafka-به-Kafka را میپوشانند. همینکه consumer در دیتابیس بنویسد یا API صدا بزند، redelivery میتواند آن اثر را تکرار کند.
- «اول
SELECTبرای چک، بعدINSERTکافی است.» دو worker هر دو میبینند «ندیدهام». unique constraint است که کار اصلی را میکند؛SELECTدر بهترین حالت بهینهسازی است. - «
ShouldBeUnique(در Laravel) job من را idempotent میکند.» این کار dispatchهای تکراری را با قفل cache حذف میکند. جلوی اجرای دوبارهٔhandle()را نمیگیرد.
ایده از کجا آمده
استدلال از تضمینهای تحویل شروع میشود. Enterprise Integration Patterns مسئله را در دو خط میگوید:
"Even when a sender application only sends a message once, the receiver application may receive the message more than once. How can a message receiver deal with duplicate messages?"
و راهحل را با دو وسیله: "Explicit 'de-duping', i.e. the removal of duplicate messages" و "Defining the message semantics to support idempotency". نام الگو Idempotent Receiver است، در گروه Messaging Endpoints. صفحهٔ Richardson در microservices.io نتیجه را برای تحویل at-least-once میگوید: "One side-effect, however, is that the consumer can be invoked repeatedly for the same message." مثال او پیام AccountDebited است که از موجودی کم میکند و "would calculate the incorrect balance". راهحلش جدول PROCESSED_MESSAGES است: بعد از شروع transaction شناسهٔ پیام insert میشود؛ چون (subscriberId, messageID) primary key است، اگر پیام قبلاً پردازش شده باشد insert شکست میخورد و handler rollback میکند و پیام را نادیده میگیرد. گزینهٔ دومی هم دارد: ذخیرهٔ شناسهها روی entityهای کسبوکاری که consumer دست میزند. مستندات طراحی Kafka نکتهٔ idempotency طبیعی را میگوید: "In many cases messages have a primary key and so the updates are idempotent (receiving the same message twice just overwrites a record with another copy of itself)". همین ایده پیش از brokerها در APIهای HTTP هم بود؛ مقالهٔ Brandur Leach در Stripe در ۲۰۱۷ مرجع معمول کلید ساختهشده توسط client است و پیشنویس IETF برای header به نام Idempotency-Key آن را استاندارد میکند (همتای HTTP).
واژهٔ inbox در عمل دو معنا دارد که در جدول inbox آمده: جدول فقط-dedup (همان PROCESSED_MESSAGES ریچاردسون) و جدول کامل دریافت که از آن بهصورت async پردازش میکنید. هر دو از همان کلید یکتا شروع میشوند.
مفاهیم، یکییکی
Idempotency و تحویل تکراری (Idempotency and duplicate delivery) حیاتی
به زبان ساده: عملیات وقتی idempotent است که دوبار انجامدادنش همان نتیجهٔ یکبار را بدهد. consumer وقتی idempotent است که دریافت دوبارهٔ یک پیام همان اثر دریافت یکبار را بگذارد.
بدفهمی رایج: «idempotent یعنی handler در بار دوم هیچ کاری نمیکند.» نه: یعنی وضعیت بعد از اجرا یکی است. handlerی که همان row را دوباره حساب و بازنویسی میکند idempotent است، حتی اگر کار کرده باشد. تلهٔ برعکس: handlerی که در بار دوم خطا برمیگرداند از دید broker idempotent نیست، چون broker تا ابد retry میکند.
تعریف: تابع f وقتی idempotent است که f(f(x)) = f(x)؛ تعریفی که EIP از ریاضی قرض میگیرد. برای پیامها: اثر N تحویل برابر اثر یک تحویل است. سه اصطلاح نزدیک اغلب با هم قاطی میشوند:
| اصطلاح | یعنی | مثال |
|---|---|---|
| Idempotent | تکرار همان وضعیت را میدهد | UPDATE orders SET status = 'paid' WHERE id = 7 |
| Safe | تکرار اصلاً چیزی را عوض نمیکند (فقط خواندن) | SELECT، GET در HTTP |
| Exactly-once (تحویل) | گیرنده فقط یک نسخه میبیند | سرتاسری ناممکن (دو ژنرال) |
| Exactly-once (اثر) | تحویل at-least-once + handler idempotent | هدف این صفحه |
Delivery 1 Delivery 2 (duplicate)
1 receive m-17
2 balance = balance + 500 -- non-idempotent: 500
3 crash before ack
4 receive m-17 again
5 balance = balance + 500 -- 1000: wrong
6 SET status='paid' -- idempotent version: same row, same valueسناریوی واقعی: واریز دوباره به کیف پول بعد از restart یک worker؛ سفارشی که دو بار shipped شده (بیضرر) در برابر دو برچسب ارسال چاپشده (بیضرر نیست)؛ ایمیل خوشآمد که بعد از timeout دو بار میرود؛ شمارندهای که بعد از هر deploy بالا میرود.
چه چیزی آن را فراهم میکند: عملیات طبیعی، کلید یکتا، یا version. بقیهٔ صفحه فهرست اینهاست.
کلید idempotency (The idempotency key) حیاتی
به زبان ساده: کلید جواب این سؤال است: «آیا این همان پیامی است که قبلاً تمامش کردهام؟» کلید غلط یا تکراری را از دست میدهد یا پیام قانونی را دور میریزد.
بدفهمی رایج: «key پیام در Kafka همان شناسهٔ پیام است.» نیست؛ آن entity را برای partitioning مشخص میکند (همهٔ رویدادهای سفارش 7 یک key دارند). پیامهای متفاوت بسیاری key یکسان دارند، و dedup روی آن همهٔ رویدادهای بعد از اولی را دور میریزد.
تعریف: هویتی پایدار و یکتا و قابلدیدن برای producer، برای یک پیام منطقی که پیش از اولین ارسال یک بار ساخته میشود و بدون تغییر در همهٔ retryها و redeliveryها میماند. دو نامزد: message id (UUID یا ULID که یک publish منطقی را مشخص میکند) و business key (order_id + "paid"، payment_id؛ معنا را مشخص میکند، پس producerی را هم میگیرد که همان واقعیت را با دو شناسه فرستاده).
Producer Broker Consumer
1 id = uuid() (ONCE)
2 publish(id, body) -----------> stored
3 confirm lost; timeout
4 publish(id, body) -----------> stored again (same id)
5 deliver ------------------> inbox(id) -> run
6 deliver (2nd copy) --------> inbox(id) -> skip
7 (if the id were regenerated at step 4 the consumer would see two different ids)کلید از کجا میآید، به تفکیک منبع:
| منبع | مثال | چه کسی میسازد | Redelivery (همان نسخه دوباره) | تکراری producer (دو نسخه) | مراقب باشید |
|---|---|---|---|---|---|
| message id ساختهشده توسط producer | uuid/ULID در header یا فیلد | Producer، یک بار | گرفته میشود | گرفته میشود، اگر در retry دوباره استفاده شود | باید قبل از اولین تلاش ساخته شود، نه داخل حلقهٔ retry |
message-id در RabbitMQ | Publishing.MessageId / Delivery.MessageId | Publisher | گرفته میشود | گرفته میشود اگر دوباره استفاده شود | اختیاری است؛ broker هرگز آن را نمیسازد یا چک نمیکند؛ خالی یعنی بدون dedup |
topic-partition-offset در Kafka | wallet.credits-3-18204 | Broker هنگام append | گرفته میشود (بعد از rebalance یا crash) | گرفته نمیشود (دو offset) | اگر topic دوباره ساخته شود reset میشود؛ offsetها per-partition هستند |
header به نام message-id در Kafka | header که producer مینویسد | Producer | گرفته میشود | گرفته میشود | به clientای نیاز دارد که headerهای record را نشان بدهد |
| entry id در Redis Streams | 1700000000000-0 | XADD | گرفته میشود (بعد از XCLAIM/XAUTOCLAIM همان id) | گرفته نمیشود (دو entry) | فیلد event_id که producer میگذارد بهتر است |
IDMP در Redis 8.6 با pid + iid | XADD s IDMP billing-1 payment-42 * ... | Producer | n/a (سمت producer) | گرفته میشود: XADD همان entry id اصلی را برمیگرداند | فقط پنجرهٔ سمت producer (IDMP-DURATION، IDMP-MAXSIZE) |
uuid در payload صف Laravel | $this->job->uuid() | Laravel هنگام dispatch | گرفته میشود | گرفته نمیشود (dispatch تازه، uuid تازه) | اگر dispatch به ازای هر نیت یک بار انجام شود کافی است |
| Business key | order_id:paid، payment_id، (aggregate_id, version) | دامنه | گرفته میشود | گرفته میشود | تکرار قانونی (بازپرداخت دوم همان سفارش) به یک discriminator نیاز دارد |
| Content hash | SHA-256 بدنه؛ IDMPAUTO در Redis | Consumer یا Redis | گرفته میشود | گرفته میشود | دو command قانونی یکسان (دو واریز «+500») با هم برخورد میکنند |
Idempotency-Key در HTTP | UUID ساختهشده توسط client | Client | گرفته میشود | گرفته میشود | بهازای هر user یا tenant دامنه بدهید |
سناریوی واقعی: سرویس پرداخت PaymentCaptured را با payment_id بهعنوان business key و یک message id تازهٔ UUID منتشر میکند؛ consumer دفتر کل روی payment_id dedup میکند (یک capture، یک ردیف دفتر)، و consumer اعلان روی message id (اعلان دوم برای همان پرداخت پیام متفاوتی است). کلیدِ فقط-offset در Kafka اجازه میدهد producer دو بار publish کند و رد شود؛ طراحی Stripe کلید را به client میدهد چون فقط client میداند «همان درخواست» یعنی چه.
چه چیزی آن را فراهم میکند: نظم در producer (شناسه را یک بار بسازید، پیش از ارسال ذخیره کنید، بهصورت header یا فیلد حمل کنید) و ایدهآل یک outbox تا شناسه همان primary key ردیف outbox باشد (Transactional Outbox).
راهحل: business key و message id را بهصورت یک رشته، با دامنهٔ consumer:
-- the dedup key is (consumer, message_id); consumer scopes it so two handlers
-- of the same message each run once
SELECT 'wallet-credit' AS consumer, 'pay_42:captured' AS message_id;جدول inbox (The inbox table) حیاتی
به زبان ساده: جدولی با یک ردیف برای هر پیامی که تمامش کردهاید. primary key اجازهٔ ردیف دوم برای همان پیام را نمیدهد.
بدفهمی رایج: «inbox صفی است که از آن میخوانم.» این یکی از دو معناست (پایینتر). در شکل فقط-dedup، inbox هرگز مثل صف خوانده نمیشود؛ فقط مجموعهای از شناسههای «انجامشده» است.
تعریف: processed_messages(consumer, message_id, processed_at) با PRIMARY KEY (consumer, message_id). ستون consumer دامنهٔ کلید است چون دو handler یک پیام هرکدام باید یک بار اجرا شوند. unique constraint همان primitive اصلی dedup است: حتی وقتی دو worker همزمان برسند دیتابیس آن را اجرا میکند، کاری که SELECT و بعد INSERT در لایهٔ برنامه نمیکند.
CREATE TABLE processed_messages (
consumer text NOT NULL,
message_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);
-- for the cleanup job (delete WHERE processed_at < now() - window)
CREATE INDEX processed_messages_processed_at_idx ON processed_messages (processed_at);ستونهای اختیاری، هرکدام با دلیلش: topic، partition، "offset" برای debug و replay؛ payload_hash برای تشخیص «همان id با بدنهٔ متفاوت» (باگ producer، همان وضعیتی که پیشنویس HTTP با 422 جواب میدهد)؛ result برای ذخیرهٔ نتیجه و replay آن؛ status و lease_until برای اثرهای غیرتراکنشی؛ received_at کنار processed_at برای اندازهگیری تأخیر. وقتی شناسهها UUID هستند برای message_id از uuid بهجای text استفاده کنید: ۱۶ بایت در برابر ۳۷.
معنای دوم: inbox کامل. بعضی تیمها «inbox» را برای بافر دریافت به کار میبرند: consumer پیام خام را در جدول inbox insert میکند (ON CONFLICT DO NOTHING)، بلافاصله بعد از commit به broker ack میدهد، و worker جداگانهای ردیفها را با FOR UPDATE SKIP LOCKED پردازش و هرکدام را processed علامت میزند. مقایسه:
| inbox فقط-dedup (Idempotent consumer) | inbox کامل (بافر دریافت) | |
|---|---|---|
| چه چیزی ذخیره میشود | فقط شناسه | کل پیام بههمراه status |
| زمان ack | بعد از transaction handler | درست بعد از insert در بافر |
| پردازش | همانجا، داخل consumer | async، از روی جدول |
| مزیتها | ساده؛ فقط یک مسیر نوشتن | broker زود آزاد میشود؛ burst را جذب میکند؛ retry و poison در SQL مدیریت میشوند |
| هزینهها | زمان handler پیام broker را نگه میدارد | صف دومی (دیتابیس شما) برای نگهداری و پاکسازی؛ تأخیر اضافه |
-- full inbox: receive
INSERT INTO inbox (consumer, message_id, payload, received_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (consumer, message_id) DO NOTHING; -- then ACK the broker
-- full inbox: process (many workers; see the SKIP LOCKED job queue in isolation-levels)
WITH next AS (
SELECT consumer, message_id FROM inbox
WHERE processed_at IS NULL
ORDER BY received_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE inbox i SET processed_at = now()
FROM next WHERE i.consumer = next.consumer AND i.message_id = next.message_id
RETURNING i.*; -- apply business effects in this same transactionتکنیک «صف روی جدول» در Isolation Levelها توضیح داده شده؛ مدیریت retry و dead-letter برای ردیفهایی که مدام شکست میخورند در Dead-Letter Queue است. بقیهٔ این صفحه دربارهٔ شکل فقط-dedup است که اول به آن نیاز دارید.
الگوی تراکنشی: بررسی، اثر و mark در یک transaction (The transactional pattern) حیاتی
به زبان ساده: سه کار را یک قدم همه-یا-هیچ کنید: شناسهٔ پیام را insert کنید، نوشتن کسبوکاری را انجام دهید، commit کنید. اگر چیزی خراب شد، نه mark هست نه نوشتن.
بدفهمی رایج: «اول SELECT 1 FROM processed_messages میزنم، پس امنم.» دو worker همزمان هیچچیز نمیبینند و هر دو جلو میروند. insertِ محافظتشده با unique constraint همان بررسی است.
تعریف: BEGIN; INSERT INTO processed_messages ... ON CONFLICT DO NOTHING; — اگر فرمان صفر ردیف گزارش کرد، پیام تکراری است: بایستید و ack بدهید. وگرنه نوشتن کسبوکاری را روی همان transaction انجام دهید و COMMIT کنید. فقط بعد از commit به broker ack بدهید.
Worker (new message m-17) Worker (redelivery of m-17)
1 BEGIN
2 INSERT processed_messages(c, m-17) -> 1 row
3 UPDATE wallets SET balance = balance + 500
4 COMMIT
5 ACK broker
6 BEGIN
7 INSERT processed_messages(c, m-17) -> 0 rows
8 ROLLBACK (nothing to undo); ACK brokerشکل بالا را اینطور بخوانید: پیام از broker وارد یک transaction واحد میشود؛ اگر insert صفر ردیف بدهد مسیر «تکراری» میشود و handler اجرا نمیشود، و اگر یک ردیف بدهد نوشتن کسبوکاری و بعد commit میآید؛ هر خطا یا crash هر دو را rollback میکند و چون ack داده نشده broker دوباره میفرستد.
سناریوی واقعی: واریز به کیف پول، کمکردن موجودی انبار، ثبت در دفتر کل، تغییر وضعیت سفارش، رزرو موجودی؛ هر چیزی که اثرش ردیفهایی در همان دیتابیسِ جدول inbox است.
چه چیزی آن را فراهم میکند:
| Store | «insert کن یا بگو وجود داشت» بهصورت atomic | نشانهٔ تکراری |
|---|---|---|
| PostgreSQL | INSERT ... ON CONFLICT (cols) DO NOTHING | command tag برابر INSERT 0 0، RowsAffected() == 0 |
| PostgreSQL (insert ساده) | INSERT و گرفتن خطا | SQLSTATE 23505 با نام unique_violation (transaction را abort میکند) |
| MySQL / InnoDB | INSERT IGNORE یا ON DUPLICATE KEY UPDATE | ۰ ردیف affected، یا ER_DUP_ENTRY (۱۰۶۲، SQLSTATE 23000) |
| SQLite | INSERT ... ON CONFLICT DO NOTHING | changes() برابر 0 |
| PostgreSQL 19 | INSERT ... ON CONFLICT DO SELECT ردیف موجود را برمیگرداند («insert یا get» idempotent) | ردیف برگشتی مال شما نیست |
| MongoDB | unique index و insertOne | خطای duplicate key |
| Redis | SET key value NX EX seconds | پاسخ nil وقتی key وجود داشته (سیستم جدا، با نوشتن دیتابیس atomic نیست) |
راهحل: Go (pgx) و Laravel پایینتر آمده. هستهٔ قابلاجرا در Go:
// Package pginbox is the inbox (idempotent consumer) pattern on pgx v5.
//
// The id of a message is inserted into processed_messages in the SAME
// transaction as the business write. The primary key is the guard: a second
// attempt inserts zero rows, so the handler is skipped.
//
// CREATE TABLE processed_messages (
// consumer text NOT NULL,
// message_id text NOT NULL,
// processed_at timestamptz NOT NULL DEFAULT now(),
// PRIMARY KEY (consumer, message_id)
// );
// CREATE INDEX processed_messages_processed_at_idx
// ON processed_messages (processed_at); -- for the cleanup job
package pginbox
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// Beginner is the part of *pgxpool.Pool (or *pgx.Conn) the inbox needs.
type Beginner interface {
Begin(ctx context.Context) (pgx.Tx, error)
}
// Result tells the caller what happened. Both values mean "acknowledge the
// message"; only an error means "leave it for redelivery".
type Result int
const (
Processed Result = iota // the handler ran and the transaction committed
Duplicate // the id was already in the inbox; handler skipped
)
func (r Result) String() string {
if r == Duplicate {
return "duplicate"
}
return "processed"
}
const markSQL = `INSERT INTO processed_messages (consumer, message_id)
VALUES ($1, $2)
ON CONFLICT (consumer, message_id) DO NOTHING`
// Handler performs the business write inside the transaction it is given.
// It must not commit or roll back; Process owns the transaction.
type Handler func(ctx context.Context, tx pgx.Tx) error
// Process runs fn at most once per (consumer, messageID): mark + side effect
// + commit in one transaction. A crash, an error or a lost connection rolls
// both back, so redelivery runs the handler again; a duplicate hits the
// primary key and is skipped.
func Process(ctx context.Context, db Beginner, consumer, messageID string, fn Handler) (Result, error) {
tx, err := db.Begin(ctx) // READ COMMITTED unless the pool says otherwise
if err != nil {
return 0, fmt.Errorf("begin: %w", err)
}
// Harmless after Commit (pgx returns ErrTxClosed); essential on every error path.
defer func() { _ = tx.Rollback(ctx) }()
tag, err := tx.Exec(ctx, markSQL, consumer, messageID)
if err != nil {
return 0, fmt.Errorf("mark: %w", err)
}
if tag.RowsAffected() == 0 {
return Duplicate, nil // already committed by someone else
}
if err := fn(ctx, tx); err != nil {
return 0, fmt.Errorf("handle: %w", err) // rollback also removes the mark
}
if err := tx.Commit(ctx); err != nil {
return 0, fmt.Errorf("commit: %w", err)
}
return Processed, nil
}
// IsUniqueViolation reports SQLSTATE 23505. You need it only when you use a
// plain INSERT instead of ON CONFLICT DO NOTHING; on PostgreSQL the failed
// statement aborts the transaction, so the caller must start a new one.
func IsUniqueViolation(err error) bool {
var pe *pgconn.PgError
return errors.As(err, &pe) && pe.Code == "23505"
}اول process بعد mark، یا اول mark بعد process (Process then mark vs mark then process) حیاتی
به زبان ساده: دو نوشتن جدا همیشه شکافی میان خود دارند. اگر در شکاف crash کنید، «اول process، بعد mark» کار را تکرار میکند و «اول mark، بعد process» آن را گم میکند.
بدفهمی رایج: «اول mark کنیم، امنتر است.» mark-اول در برابر تکراری امن است و در برابر گمشدن ناامن: crash بعد از mark و پیش از اثر یعنی redelivery رد میشود و کار آن پیام هرگز انجام نمیشود. بیآنکه بفهمید at-least-once را به at-most-once تبدیل کردهاید.
تعریف: ترتیب فقط وقتی مهم است که دو نوشتن در transactionهای جدا باشند. در یک transaction ترتیب بیاهمیت است، چون هر دو با هم لغو میشوند.
A. process then mark (two commits)
1 receive m-17
2 UPDATE wallets ... COMMIT -- effect done
3 ---- crash ----
4 (mark never written)
5 redelivery: no mark -> UPDATE again -> balance +1000 DUPLICATE
B. mark then process (two commits)
1 receive m-17
2 INSERT mark ... COMMIT -- mark durable
3 ---- crash ----
4 (effect never applied)
5 redelivery: mark exists -> skipped -> balance +0 LOST
C. one transaction (inbox)
1 BEGIN; INSERT mark; UPDATE wallets;
2 ---- crash ---- -> both undone
3 redelivery: no mark -> BEGIN; INSERT mark; UPDATE; COMMIT CORRECTسه ردیف شکل را با سه بلوک بالا تطبیق دهید: A و B هر دو دو commit دارند و crash در شکاف یکی را تکراری و دیگری را گمشده میکند؛ فقط C، که mark و اثر را در یک transaction میگذارد، درست است، آن هم وقتی اثر در همان دیتابیسِ جدول inbox باشد.
سناریوی واقعی: کلید «دیدهشده» با SET NX در Redis بهاضافهٔ نوشتن در دیتابیس، از ریشه A یا B است (دو سیستم، بدون transaction مشترک). حادثهٔ کلاسیک production همان B پشت یک cache است: key ست شد، worker مرد، و هر retry جواب «قبلاً پردازش شده» گرفت.
چه چیزی جلوی آن را میگیرد: یک transaction، در یک دیتابیس، که هر دو نوشتن را دارد. وقتی اثر جای دیگری است به claim، perform، complete برمیگردید.
| طراحی | شکاف crash | نتیجه | چه وقت قابلقبول است |
|---|---|---|---|
| اول process بعد mark (دو commit) | اثر انجام شده، mark نیست | اثر تکراری | اثر idempotency طبیعی دارد |
| اول mark بعد process (دو commit) | mark هست، اثر نیست | پیام گمشده | اثر اختیاری است و تکراری از جاافتادن بدتر است (ایمیل تبلیغاتی) |
| همان transaction | ندارد | Effectively-once | اثر در دیتابیس inbox است |
| Claim، perform، complete (lease) | اثر انجام شده، «done» نیست | اثر با همان کلید پاییندستی تکرار میشود | اثر بیرونی است و پاییندستی dedup میکند |
تکراریهای همزمان (Concurrent duplicates) مهم
به زبان ساده: گاهی تکراری دیرتر نمیرسد، همزمان میرسد: handler کند از visibility timeout بیرون میزند، broker همان پیام را به worker دوم میدهد، و حالا دو worker با هم کار میکنند.
بدفهمی رایج: «worker دوم mark مال اولی را میبیند.» تا وقتی اولی commit نکرده نمیبیند. mark تا آن لحظه نامرئی است؛ دقیقاً به همین دلیل بررسی با SELECT شکست میخورد و unique constraint مهم است.
تعریف: بررسی یکتایی index در PostgreSQL آن را حل میکند: "If a conflicting row has been inserted by an as-yet-uncommitted transaction, the would-be inserter must wait to see if that transaction commits. If it rolls back then there is no conflict. If it commits without deleting the conflicting row again, there is a uniqueness violation." مستندات INSERT اضافه میکند که جدولهای دارای unique index "might block if concurrent sessions perform actions that lock or modify rows matching the unique index values being inserted". با ON CONFLICT DO NOTHING، «violation» به «صفر ردیف insert شد» تبدیل میشود.
Worker A (m-17) Worker B (m-17, duplicate)
1 BEGIN
2 INSERT mark(m-17) -> 1 row
3 BEGIN
4 INSERT mark(m-17) ... BLOCKS (A uncommitted)
5 UPDATE wallets ...
6 COMMIT (unblocks) -> INSERT 0 0 -> duplicate, ACK
-- variant: A rolls back at step 6 (unblocks) -> INSERT 0 1 -> B runs the handlerسناریوی واقعی: consumer کافکا که پردازشش از max.poll.interval.ms بیشتر میشود و از group بیرون انداخته میشود در حالی که handler هنوز کار میکند؛ پیام SQS که visibility timeoutاش تمام شده؛ entry در Redis که XAUTOCLAIM شده در حالی که worker اصلی فقط کند است؛ retry_after در Laravel که کوتاهتر از job است.
چه چیزی جلوی آن را میگیرد: unique constraint بهعلاوهٔ transactionهای کوتاه. چون B منتظر A میماند، transaction handler را از فراخوانیهای کند (HTTP، sleep) خالی نگه دارید تا B مدت زیادی یک connection را اشغال نکند؛ lock_timeout بگذارید تا تکراری بلوکشده با SQLSTATE 55P03 کنار برود و requeue شود نه اینکه pool را بگیرد (Connection Pooling). در READ COMMITTED (پیشفرض PostgreSQL) ممکن است ON CONFLICT DO NOTHING بهحق ردیفی را رد کند "due to the outcome of another transaction whose effects are not visible to the INSERT snapshot"؛ این همان حالت بالاست و همان چیزی است که میخواهید.
راهحل: کد الگوی تراکنشی از قبل در برابر race امن است؛ وقتی تکراری زیاد است SET LOCAL lock_timeout = '2s' را داخل transaction اضافه کنید.
Idempotency طبیعی (Natural idempotency) حیاتی
به زبان ساده: گاهی جدول لازم نیست، چون تکرار عملیات چیزی را عوض نمیکند: مقدار را set کنید نه اینکه به آن اضافه کنید، با key upsert کنید، وضعیت را فقط یک بار جلو ببرید.
بدفهمی رایج: «upsert همیشه idempotent است.» upsertی که اضافه میکند (ON CONFLICT DO UPDATE SET qty = qty + EXCLUDED.qty) نیست. فقط وقتی idempotent است که update مقداری بنویسد که به مقدار قبلی وابسته نباشد.
تعریف: عملیاتی که اعمال مکرر آن به همان وضعیت همگرا میشود.
| عملیات | Idempotent؟ | چرا | بازنویسی idempotent |
|---|---|---|---|
SET status = 'paid' | بله | هر بار همان مقدار | لازم نیست |
INSERT ... ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status | بله | مقدار جدید را مینویسد نه delta | لازم نیست |
UPDATE orders SET status = 'paid' WHERE id = 7 AND status = 'pending' | بله | شرطی: فقط اولی عوضش میکند | لازم نیست |
balance = balance + 500 | نه | به مقدار قبلی وابسته است | inbox، یا هر واریز را بهصورت ردیف دفتر با message id ذخیره و موجودی را حساب کنید |
likes = likes + 1 | نه | شمارنده | جدول یکتای (post_id, user_id)؛ ردیفها را بشمارید |
| append به list/log | نه | هر بار بزرگتر میشود | هر entry را با message id کلید بزنید |
| ارسال ایمیل، فراخوانی API | نه | اثر بیرونی | کلید پاییندستی |
| حذف با id | بله | رفته، رفته است (DELETE دوم ۰ ردیف را affect میکند) | لازم نیست |
| ساخت با id انتخابی client | بله | ساخت دوم conflict میدهد یا نادیده گرفته میشود | لازم نیست |
-- set, not add
UPDATE orders SET status = 'paid' WHERE id = 7;
-- upsert by business key
INSERT INTO order_projection (order_id, status) VALUES ('o-1', 'paid')
ON CONFLICT (order_id) DO UPDATE SET status = EXCLUDED.status;
-- move forward once
UPDATE orders SET status = 'paid' WHERE id = 7 AND status = 'pending';
-- counter as a set: replay-safe
INSERT INTO post_likes (post_id, user_id) VALUES (9, 42) ON CONFLICT DO NOTHING;سناریوی واقعی: read modelها و search indexها (سند را از وضعیت فعلی بازبسازید)، ستونهای last_seen_at، گذار وضعیت، ابطال cache، همگامسازی feature flag. log compaction در Kafka آخرین record هر key را نگه میدارد، که فقط وقتی معنا دارد که recordها snapshotهای idempotent باشند.
چه چیزی آن را فراهم میکند: انتخابهای schema: کلید یکتا، جدولهای set بهجای شمارنده، ردیف دفتر بهجای موجودی، update شرطی. پیش از افزودن inbox اینها را ترجیح دهید.
اثرهای جانبی غیرتراکنشی (Non-transactional side effects) مهم
به زبان ساده: ایمیل، فراخوانی پرداخت یا webhook بیرون از دیتابیس شماست. inbox نمیتواند «بفرست و ثبت کن» را atomic کند، پس باید انتخاب کنید کدام شکست را ترجیح میدهید: دوبار فرستاده شود، یا هیچوقت.
بدفهمی رایج: «transaction دور فراخوانی HTTP مشکل را حل میکند.» transaction ردیفهای شما را rollback میکند؛ ایمیل رفته است. باز نگهداشتن transaction دیتابیس روی یک فراخوانی شبکهای هم تکراریهای همزمان را بلوک میکند و pool را تمام میکند.
تعریف: برای اثر بیرونی شکاف crash را بهصورت محلی نمیتوان بست؛ پس (الف) خود فراخوانی پاییندستی را با کلیدی که از message id ساختهاید idempotent میکنید، (ب) اثر را با lease دنبال میکنید تا crash کشف و جبران شود، یا (ج) اثر را در outbox میگذارید تا relay آن را at-least-once در برابر پاییندستیِ dedupکننده انجام دهد.
Consumer Inbox row Mail provider
1 claim(m-17) ------------------> processing, lease 120 s
2 POST /send Idempotency-Key: welcome:m-17 --------------> sends, stores key
3 ---- crash before 4 ----
4 (lease expires)
5 redelivery: claim(m-17) lease expired -> re-claimed
6 POST /send same key ----------------------------------> returns the first result
7 complete(m-17) ----------------> doneسناریوی واقعی: ایمیل خوشآمد، SMS، capture پرداخت با PSP، ساخت برچسب ارسال، webhook برای مشتری، صدا زدن سیستم قدیمی SOAP. API استریپ روی POST کلید idempotency میپذیرد و نتیجهٔ اول را replay میکند؛ API ایمیل معمولی نمیپذیرد، پس برای ایمیل بر اساس پیامد کسبوکاری انتخاب میکنید: at-least-once (مزاحمت) یا at-most-once (هرگز نرسد).
چه چیزی آن را فراهم میکند:
| تکنیک | چگونه | مزیت | هزینه یا محدودیت |
|---|---|---|---|
| کلید idempotency پاییندستی | header مثل Idempotency-Key: consumer:message_id | سادهترین؛ state اضافه ندارد | پاییندستی باید پشتیبانی کند و پنجرهٔ کافی داشته باشد (Stripe مستند کرده کلیدها ممکن است بعد از دستکم ۲۴ ساعت حذف شوند) |
| Claim، perform، complete | ردیف inbox با status و lease_until؛ ON CONFLICT DO UPDATE ... WHERE status = 'processing' AND lease_until < now() | crash را کشف میکند؛ همزمانی را محدود میکند | بعد از انقضای lease ممکن است اثر تکرار شود؛ هنوز به کلید پاییندستی نیاز دارد |
| اثر را outbox کنید | handler ردیف outbox به نام send_email را در transaction کسبوکاری مینویسد؛ relay میفرستد | handler تراکنشی میماند؛ retry جدا میشود | قطعهٔ متحرک دیگر؛ at-least-once در relay |
| اول هدف را بررسی کنید | پیش از POST با GET پرداخت را با reference خودتان بخوانید | با بعضی APIها بدون کلید کار میکند | میان بررسی و عمل race دارد؛ تأخیر اضافه |
| تکراری را بپذیرید | هیچ کاری نکنید | هزینهٔ صفر | فقط وقتی بیضرر است (log، metric، refresh) |
جفت Outbox + inbox. در دو سرویس، این جفت دستور استاندارد است: outbox تولیدکننده تضمین میکند هر رویداد حداقل یک بار منتشر میشود، inbox مصرفکننده تضمین میکند حداکثر یک بار اعمال میشود، و با هم میان دو دیتابیس effectively-once میشوند.
در شکل، سرویس A ردیف کسبوکاری و ردیف outbox را در یک transaction مینویسد، relay حداقل یک بار publish میکند (ممکن است بعد از crash دوباره بفرستد)، و سرویس B با inbox و نوشتن کسبوکاری در یک transaction نسخهٔ دوم را بیاثر میکند.
راهحل: Go (claim، perform با کلید پاییندستی، complete) و معادل Laravel در بخشهای پایین آمده است.
TTL، پنجرهٔ dedup و پاکسازی (TTL, dedup window and cleanup) حیاتی
به زبان ساده: جدول با هر پیام بزرگتر میشود. ردیف dedup فقط باید تا وقتی زنده بماند که ممکن است تکراری برسد؛ بعدش بار اضافه است.
بدفهمی رایج: «یک روز نگه دارید، کلی کافی است.» عدد درست محاسبه میشود، حدسی نیست: زود منقضی کنید، تکراری دیررس بیصدا دوباره اجرا میشود؛ دیر منقضی کنید، جدول و index و هزینهٔ vacuum بیفایده بزرگ میشوند.
تعریف: پنجرهٔ dedup (dedup window) بلندترین فاصله میان اولین تحویل یک پیام و آخرین تحویل ممکن یک نسخهٔ آن است. مجموع مسیرهای redelivery است: سازوکار redelivery خود broker (visibility timeout، retry_after، زمان idle در pending entry، retention در Kafka برای replay)، برنامهٔ retry و backoff، بیشترین زمانی که پیام ممکن است قبل از replay در DLQ بماند، و افق retry خود producer، بهاضافهٔ یک حاشیه. TTL ردیف همان پنجره است.
t=0 first delivery, mark written
t=5s broker redelivery (visibility timeout)
t=2min retry with backoff
t=1h message returns from DLQ replay
t=24h producer's retry job resends (outbox relay recovered after an outage)
t=7d longest path + margin -> TTL = 7 d; before this a duplicate must be caughtbrokerها همین مسئله را در سمت producer چطور محدود میکنند:
| سیستم | کلید dedup | پنجره | توضیح |
|---|---|---|---|
| Amazon SQS FIFO | MessageDeduplicationId | ۵ دقیقه | حتی بعد از دریافت و حذف پیام هم شناسه را دنبال میکند |
| Azure Service Bus | MessageId (با PartitionKey وقتی partitioned است) | پیشفرض ۱۰ دقیقه؛ از ۲۰ ثانیه تا ۷ روز | scheduled messageها هم حساب میشوند؛ پنجرهٔ بزرگتر throughput را کم میکند |
| NATS JetStream | header به نام Nats-Msg-Id | پیشفرض ۲ دقیقه (--dupe-window) | فقط id بررسی میشود، نه بدنه |
| Apache Pulsar | نام producer (broker تکراریها را per producer فیلتر میکند) | در snapshotهای dedup نگهداری میشود؛ بهطور پیشفرض خاموش (brokerDeduplicationEnabled=false)؛ وضعیت producer بهطور پیشفرض بعد از ۶ ساعت بیکاری دور ریخته میشود | نام producer اجباری است؛ message timeout را روی 0 بگذارید |
| Redis Streams 8.6+ | IDMP با pid + iid | IDMP-DURATION پیشفرض ۱۰۰ ثانیه (از ۱ تا ۸۶۴۰۰)؛ IDMP-MAXSIZE پیشفرض ۱۰۰ بهازای هر producer (از ۱ تا ۱۰۰۰۰) | iids-duplicates را در XINFO STREAM پایش کنید |
| Kafka | شمارهٔ sequence در idempotent producer | فقط session همان producer | پنجرهٔ زمانی نیست؛ با producer id تازه reset میشود |
هیچکدام redelivery سمت consumer را بعد از پنجرهٔ خودشان نمیپوشانند. inbox بقیه را با پنجرهای که خودتان کنترل میکنید میپوشاند.
راهبردهای پاکسازی:
| راهبرد | چگونه | مزیت | محدودیت |
|---|---|---|---|
DELETE دستهای | job زمانبندیشده: ردیفهای قدیمیتر از پنجره را در دستههای کوچک حذف کن (index روی processed_at) | ساده | dead tuple و WAL تولید میکند؛ به جای کافی برای autovacuum نیاز دارد |
| Partition و drop | بر اساس روز partition کنید، partitionهای قدیمی را DROP یا DETACH کنید | آنی، بدون VACUUM («far faster than a bulk operation» در مستندات PostgreSQL) | unique key در جدول partitioned باید partition key را داشته باشد |
| Store با TTL | EXPIRE در Redis / TTL در DynamoDB بهعنوان store dedup | خودش پاک میشود | با نوشتن دیتابیس atomic نیست |
| برای همیشه نگه دارید | هرگز حذف نکنید | پنجرهٔ dedup بینهایت | هزینه با throughput رشد میکند؛ در حجم کم مشکلی نیست |
-- batched delete (PostgreSQL has no DELETE ... LIMIT)
DELETE FROM processed_messages
WHERE (consumer, message_id) IN (
SELECT consumer, message_id FROM processed_messages
WHERE processed_at < now() - interval '14 days'
ORDER BY processed_at LIMIT 5000
);تلهٔ partitioning. PostgreSQL میگوید unique یا primary key روی جدول partitioned "must include all of the partition key columns". اگر بر اساس processed_at (زمان پردازش) partition کنید، کلید (consumer, message_id, processed_at) میشود و تکراریِ پردازششده یک روز بعد processed_at متفاوتی دارد، پس پذیرفته میشود: بیصدا dedup میانروزی را از دست دادهاید. بر اساس یک ویژگی از خود پیام partition کنید که روی هر نسخه یکسان است (timestamp که producer گذاشته یا بخش زمانی ULID):
CREATE TABLE processed_messages (
consumer text NOT NULL,
message_id text NOT NULL,
occurred_at timestamptz NOT NULL, -- from the message, identical on every copy
PRIMARY KEY (consumer, message_id, occurred_at)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE processed_messages_2026_11_25 PARTITION OF processed_messages
FOR VALUES FROM ('2026-11-25') TO ('2026-11-26');
-- retire a day: DROP TABLE processed_messages_2026_11_18;
-- the conflict target must name the partition key too:
-- ... ON CONFLICT (consumer, message_id, occurred_at) DO NOTHINGاندازهگیری. تعداد ردیف = نرخ پیام × پنجره. تخمین خودمان برای حجم برای ردیف با شناسهٔ text حدود ۱۰۰ تا ۱۵۰ بایت است، شامل entry در index کلید اصلی (برای جدول خودتان با pg_total_relation_size اندازه بگیرید):
| نرخ | پنجره | ردیفها | حجم تقریبی با ۱۲۰ بایت برای هر ردیف |
|---|---|---|---|
| ۱۰ پیام در ثانیه | ۷ روز | ۶ میلیون | کمتر از ۱ گیگابایت |
| ۱۰۰ پیام در ثانیه | ۷ روز | ۶۰ میلیون | حدود ۷ گیگابایت |
| ۱٬۰۰۰ پیام در ثانیه | ۱۴ روز | ۱٫۲ میلیارد | حدود ۱۴۵ گیگابایت |
| ۱۰٬۰۰۰ پیام در ثانیه | ۷ روز | ۶ میلیارد | حدود ۷۲۵ گیگابایت: partition کنید، کوتاه کنید، یا جدول را حذف کنید |
معاملهٔ retention در برابر پنجرهٔ dedup. پنجرهٔ بلندتر یعنی replay امنتر و بازگشت دیرهنگام از DLQ امنتر، ولی جدول و index بزرگتر و پاکسازی پرتلاطمتر. پنجرهٔ کوتاهتر یعنی جدول کوچکتر و خطر اینکه تکراری دیررس (relay outbox که بعد از قطعی یکروزه برگشته، DLQ که بعد از یک هفته replay میشود، topic که از offset صفر دوباره خوانده میشود) دوباره اعمال شود. دو قاعدهٔ عملی: پنجره دستکم باید به اندازهٔ بلندترین مسیر replay یا تأخیر برنامهریزیشده باشد؛ و برای replay عمدی (بازسازی projection از topic کافکا) یک نام consumer تازه بگذارید که دامنهٔ dedup تازه است، یا به projectionهای versionدار تکیه کنید که اصلاً جدول نمیخواهند.
Projectionهای idempotent (Idempotent projections) مهم
به زبان ساده: read modelی که از رویدادها ساخته میشود باید هم رسیدن دوبارهٔ یک رویداد را تحمل کند و هم رسیدن رویداد قدیمیتر بعد از جدیدتر را. شمارهٔ version هر دو حالت را بیاثر میکند.
بدفهمی رایج: «با timestamp رویداد جدیدترین را نگه میداریم.» ساعت producerهای مختلف با هم نمیخواند. از version یا شمارهٔ sequence هر aggregate که مالک aggregate میدهد استفاده کنید.
تعریف: رویداد را فقط وقتی اعمال کنید که versionاش از version ذخیرهشده بیشتر باشد: INSERT ... ON CONFLICT (id) DO UPDATE ... WHERE projection.version < EXCLUDED.version. replay (version مساوی) و رویداد کهنه (version کمتر) صفر ردیف را عوض میکنند. با Optimistic در برابر Pessimistic Locking مقایسه کنید: version column روی read model همان ایدهٔ compare-and-set است که روی پیامها اعمال میشود.
Messages arrive: v3, v3 (dup), v2 (late), v4
1 v3 -> INSERT, rows=1, projection = v3
2 v3 -> conflict, WHERE 3 < 3 false, rows=0 (duplicate ignored)
3 v2 -> conflict, WHERE 3 < 2 false, rows=0 (stale ignored)
4 v4 -> conflict, WHERE 3 < 4 true, rows=1 (applied)دقیقاً همین دنبالهٔ statementها را روی SQLite 3 اجرا کردیم (همان syntax ON CONFLICT ... DO UPDATE ... WHERE) تا شمارشهای بالا را بسنجیم: 1, 0, 0, 1 و ردیف نهایی o-1 | shipped | 4 بود.
سناریوی واقعی: read modelهای وضعیت سفارش، سندهای search index، cache پروفایل مشتری، جدولهای materialize مثل «سفارشها در روز»، هر چیزی که از رویدادهای Event Sourcing و CQRS تغذیه میشود.
چه چیزی آن را فراهم میکند / محدودیتها: version در envelope پیام (طراحی پیام و Schema Evolution). version < پرش را میپذیرد (v3 بعد v5)، که وقتی رویدادها snapshot کامل وضعیتاند درست است؛ وقتی رویدادها delta هستند شکاف یعنی رویداد گمشده، پس version = stored + 1 را الزام کنید و در شکاف park یا retry کنید (ترتیب و Partitioning). شمارندهها: count + 1 ذخیره نکنید؛ از مجموعهٔ شناسهها دوباره بشمارید یا شمارش را با version آخرین رویداد شامل ذخیره کنید.
راهحل: Go و Laravel:
// Package projection updates a read model from events that may arrive twice
// and out of order. A version column turns "apply" into "apply only if newer",
// which is naturally idempotent: replays and stale events are no-ops.
//
// CREATE TABLE order_projection (
// order_id text PRIMARY KEY,
// status text NOT NULL,
// version bigint NOT NULL,
// updated_at timestamptz NOT NULL DEFAULT now()
// );
package projection
import (
"context"
"github.com/jackc/pgx/v5/pgconn"
)
// OrderEvent carries the aggregate's version assigned by the producer.
type OrderEvent struct {
OrderID string
Status string
Version int64
}
const upsertSQL = `INSERT INTO order_projection (order_id, status, version)
VALUES ($1, $2, $3)
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status, version = EXCLUDED.version, updated_at = now()
WHERE order_projection.version < EXCLUDED.version`
// Execer is satisfied by pgx.Tx, *pgx.Conn and *pgxpool.Pool.
type Execer interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}
// Apply returns true when the event changed the projection, false when it was
// a duplicate (same version) or stale (older version).
func Apply(ctx context.Context, db Execer, e OrderEvent) (bool, error) {
tag, err := db.Exec(ctx, upsertSQL, e.OrderID, e.Status, e.Version)
if err != nil {
return false, err
}
return tag.RowsAffected() == 1, nil
}<?php
namespace App\Projections;
use Illuminate\Support\Facades\DB;
// A read model that tolerates duplicate AND out-of-order events: apply an
// event only if its version is newer than the stored one. A replay (same
// version) and a stale event (older version) both change zero rows.
final class ProjectionUpsert
{
public static function apply(string $orderId, string $status, int $version): bool
{
$changed = DB::affectingStatement(
'INSERT INTO order_projection (order_id, status, version, updated_at)
VALUES (?, ?, ?, now())
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status,
version = EXCLUDED.version,
updated_at = now()
WHERE order_projection.version < EXCLUDED.version',
[$orderId, $status, $version],
);
return $changed === 1;
}
}Offset کنار خروجی (Offsets stored with the output) تکمیلی
به زبان ساده: بهجای یک ردیف dedup برای هر پیام، یک ردیف برای هر partition نگه دارید: «تا offset شمارهٔ N اعمال کردهام»، که در همان transaction نوشتن کسبوکاری بهروز میشود. بعد از restart به N بروید.
بدفهمی رایج: «exactly-once کافکا این را میپوشاند.» Kafka-به-Kafka را میپوشاند. برای خروجی دیتابیس، مستندات طراحی Kafka دقیقاً همین را توصیه میکند: "letting the consumer store its offset in the same place as its output."
تعریف: kafka_offsets(group, topic, partition, next_offset)، در transaction کسبوکاری با یک guard (WHERE next_offset <= record_offset) جلو میرود؛ هنگام assign شدن partition، موقعیت consumer از این جدول تنظیم میشود.
سناریوی واقعی: sink پرحجم Kafka به PostgreSQL با صدها هزار record در ثانیه که یک ردیف بهازای هر پیام برایش گران است؛ batch loaderهایی که یک batch و offset پایانیاش را با هم commit میکنند.
چه چیزی آن را فراهم میکند / محدودیتها: مصرف ordered و partition-aware میخواهد (موقعیت per-partition معنا دارد)، transactionی که همهٔ اثرها را شامل شود، و دقت در rebalance (offset ذخیرهشده است که حقیقت است، نه offset commitشدهٔ broker). producerی را که همان رویداد را در دو offset نوشته dedup نمیکند. طرح compile-only در Go:
// Package main sketches the other way to get exactly-once EFFECT from Kafka
// into a database without a per-message inbox: store the consumer position
// in the same database transaction as the business write, and seek to it on
// assignment. Kafka's design notes describe it as letting "the consumer store
// its offset in the same place as its output". Compile-only sketch.
//
// CREATE TABLE kafka_offsets (
// consumer_group text NOT NULL,
// topic text NOT NULL,
// partition int NOT NULL,
// next_offset bigint NOT NULL,
// PRIMARY KEY (consumer_group, topic, partition)
// );
package main
import (
"context"
"log"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/twmb/franz-go/pkg/kgo"
)
const group = "wallet-credit"
// seekToStored runs when partitions are assigned: it overrides Kafka's
// committed offset with the position stored next to the data.
func seekToStored(pool *pgxpool.Pool) func(context.Context, *kgo.Client, map[string][]int32) {
return func(ctx context.Context, cl *kgo.Client, assigned map[string][]int32) {
set := map[string]map[int32]kgo.EpochOffset{}
for topic, parts := range assigned {
for _, p := range parts {
var next int64
err := pool.QueryRow(ctx,
`SELECT next_offset FROM kafka_offsets
WHERE consumer_group = $1 AND topic = $2 AND partition = $3`,
group, topic, p).Scan(&next)
if err != nil {
continue // no row yet: keep the broker's starting position
}
if set[topic] == nil {
set[topic] = map[int32]kgo.EpochOffset{}
}
set[topic][p] = kgo.EpochOffset{Epoch: -1, Offset: next}
}
}
cl.SetOffsets(set)
}
}
// apply writes the business row and advances the stored offset atomically.
// The guard makes a replayed record (offset below next_offset) a no-op.
func apply(ctx context.Context, tx pgx.Tx, r *kgo.Record, walletID string, amount int64) error {
tag, err := tx.Exec(ctx,
`INSERT INTO kafka_offsets (consumer_group, topic, partition, next_offset)
VALUES ($1, $2, $3, $4)
ON CONFLICT (consumer_group, topic, partition) DO UPDATE
SET next_offset = EXCLUDED.next_offset
WHERE kafka_offsets.next_offset <= $5`,
group, r.Topic, r.Partition, r.Offset+1, r.Offset)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return nil // already applied: stored position is past this record
}
_, err = tx.Exec(ctx, `UPDATE wallets SET balance = balance + $1 WHERE id = $2`, amount, walletID)
return err
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
cl, err := kgo.NewClient(
kgo.SeedBrokers("localhost:9092"),
kgo.ConsumerGroup(group),
kgo.ConsumeTopics("wallet.credits"),
kgo.DisableAutoCommit(), // the database is the source of truth
kgo.OnPartitionsAssigned(seekToStored(pool)),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
_ = apply // called per record inside pool.BeginFunc in real code
}Idempotency-Key در لبهٔ HTTP (Idempotency-Key at the HTTP edge) تکمیلی
به زبان ساده: همین الگو برای HTTP: client یک Idempotency-Key یکتا میفرستد، سرور اولین پاسخ را به یاد میسپارد و در retry همان را برمیگرداند.
بدفهمی رایج: «POST را هرگز نمیشود retry کرد.» با کلید میشود. Leach خرابیای را که این رفع میکند توصیف میکند: برای endpointی که پول برمیدارد، "accidentally calling it twice would lead to the customer being double-charged, which is very bad".
تعریف: پیشنویس IETF header را مقداری یکتا که client میسازد تعریف میکند "which the resource uses to recognize subsequent retries of the same request". استفادهٔ دوباره از کلید با payload متفاوت باید 422 بدهد، retry در حالی که درخواست اول هنوز در جریان است 409، و انقضا سیاست سرور است ("The resource SHOULD define such expiration policy and publish it in the documentation"). هنوز Internet-Draft است، پس جزئیات را موقتی بدانید. Stripe کلیدهایی تا ۲۵۵ نویسه را مستند کرده و میگوید کلیدها ممکن است بعد از دستکم ۲۴ ساعت حذف شوند.
چه چیزی آن را فراهم میکند: جدول یا cache با کلید (tenant، key) که fingerprint درخواست، state (in_progress/done) و پاسخ را نگه دارد. برای پول، کلید را در جدولی داخل transaction نوشتن بگذارید؛ claim فقط-cache (مثل middleware لاراول پایین) برای endpointهای کمریسک مناسب است.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
// HTTP flavour of the same idea: the client picks the key, the server
// remembers the first response and replays it. Register on mutating routes:
// Route::post('/payments', ...)->middleware(IdempotencyKey::class);
//
// Simplification: this middleware stores the response in the cache, so the
// "claim" and the business write are NOT in one transaction. For money, put
// the key in a table and insert it in the same transaction as the write.
class IdempotencyKey
{
public function handle(Request $request, Closure $next): Response
{
$key = $request->header('Idempotency-Key');
if ($key === null || $key === '') {
return $next($request);
}
$fingerprint = hash('sha256', $request->method().$request->path().$request->getContent());
$cacheKey = 'idem:'.$request->user()?->getAuthIdentifier().':'.$key;
// Cache::add is atomic: only the first caller claims the key.
$claimed = Cache::add($cacheKey, ['state' => 'in_progress', 'fingerprint' => $fingerprint], now()->addHours(24));
if (! $claimed) {
$entry = Cache::get($cacheKey);
if (($entry['fingerprint'] ?? null) !== $fingerprint) {
return response()->json(['error' => 'Idempotency-Key reused with a different request'], 422);
}
if (($entry['state'] ?? null) === 'in_progress') {
return response()->json(['error' => 'A request with this key is still being processed'], 409);
}
return response($entry['body'], $entry['status'])
->header('Content-Type', $entry['content_type'])
->header('Idempotent-Replayed', 'true');
}
try {
$response = $next($request);
} catch (\Throwable $e) {
Cache::forget($cacheKey); // let the client retry after a crash
throw $e;
}
if ($response->getStatusCode() >= 500) {
Cache::forget($cacheKey);
return $response;
}
Cache::put($cacheKey, [
'state' => 'done',
'fingerprint' => $fingerprint,
'status' => $response->getStatusCode(),
'body' => $response->getContent(),
'content_type' => $response->headers->get('Content-Type', 'application/json'),
], now()->addHours(24));
return $response;
}
}سازوکار (Mechanics)
هر store چه primitive dedup میدهد
| Store | Primitive | با نوشتن کسبوکاری atomic است؟ | نشانهٔ شکست | نکته |
|---|---|---|---|---|
| PostgreSQL | unique/PK index + ON CONFLICT DO NOTHING | بله (همان transaction) | 23505 یا ۰ ردیف | منتظر insert تداخلی commitنشده میماند |
| MySQL / InnoDB | unique/PK + INSERT IGNORE یا ON DUPLICATE KEY UPDATE | بله | ER_DUP_ENTRY 1062، SQLSTATE 23000 | IGNORE خطاها را به warning پایین میآورد، پس میتواند خطاهای غیرتکراری را هم پنهان کند (مرجع MySQL از این دستگاه قابلدریافت نبود؛ جزئیات را آنجا بررسی کنید) |
| SQLite | INSERT ... ON CONFLICT DO NOTHING | بله | changes() = 0 | یک writer: race نیست، ولی باز transaction لازم است |
| MongoDB | unique index | فقط با transaction چندسندی | خطای duplicate key | insert-then-act بدون transaction همان mark-then-process است |
| Redis | SET key v NX EX n | نه (سیستم جدا) | پاسخ nil | eviction یا failover ماركرا از بین میبرد: تکراری برمیگردد |
| DynamoDB / Cassandra | نوشتن شرطی (attribute_not_exists، IF NOT EXISTS) | فقط داخل یک item یا partition | شکست شرط | atomicity میانitem محدود است |
تنظیمات طراحی جدول
| تنظیم | انتخاب | چرا |
|---|---|---|
| ستونهای کلید | (consumer, message_id) | دامنه بهازای هر handler؛ یک id ممکن است چند handler داشته باشد |
| نوع کلید | uuid یا text | uuid ۱۶ بایت است؛ شناسهٔ text حدود ۳۷ بایت بهعلاوهٔ سربار index |
| Index | فقط PK و processed_at | هر index اضافه تقویت نوشتن (write amplification) در داغترین مسیر insert است |
| Fill factor | پیشفرض | جدول تا پاکسازی فقط-insert است |
| Isolation | READ COMMITTED | ON CONFLICT از قبل روی key سریال میکند؛ levelهای بالاتر 40001 و retry اضافه میکنند (Isolation Levelها) |
lock_timeout | چند ثانیه | تکراری بلوکشده کنار میکشد (55P03) نه اینکه connection را نگه دارد |
| Autovacuum | برای دستههای delete تنظیم کنید | پاکسازی dead tuple میسازد (MVCC و VACUUM) |
| محل قرارگیری | همان دیتابیس و shard جدولهای کسبوکاری | وگرنه mark و اثر atomic نیستند (Storage و Data Scaling) |
کدهای خطا و نشانههایی که میبینید
| نشانه | کجا | معنا | چه کنیم |
|---|---|---|---|
INSERT 0 0 / RowsAffected() = 0 | PostgreSQL با ON CONFLICT DO NOTHING | تکراری | رد کنید و ack بدهید |
SQLSTATE 23505 با نام unique_violation | PostgreSQL، insert ساده | تکراری؛ transaction abort شده | rollback، بهعنوان تکراری ببینید، ack بدهید |
ER_DUP_ENTRY 1062 (SQLSTATE 23000) | MySQL | تکراری | همان |
SQLSTATE 40001، 40P01 | PostgreSQL | serialization failure، deadlock | کل transaction را retry کنید (Deadlock) |
SQLSTATE 55P03 با نام lock_not_available | PostgreSQL با lock_timeout | تکراری همزمان key را نگه داشته | nack و requeue، یا بعد از مکث رد کنید |
redelivered = true | تحویل RabbitMQ | شاید قبلاً دیده شده (فقط hint) | محتاط باشید؛ باز هم از inbox استفاده کنید |
redelivered ست نشده | تحویل RabbitMQ | تضمین شده این queue قبلاً آن را ندیده | تنها حالتی که flag چیزی را ثابت میکند |
UniqueConstraintViolationException | Laravel (Illuminate\Database) | تکراری در insert ساده | بیرون از transaction بگیرید |
ErrTxClosed | pgx | Rollback بعد از Commit | در rollbackِ deferred نادیده بگیرید |
راهحل مسئلههای کلاسیک (Solving the classic problems)
| مسئله | راهحل | چگونه | مزیت | هزینه یا محدودیت |
|---|---|---|---|---|
| واریز دوباره بعد از restart | inbox در transaction کسبوکاری | INSERT ... ON CONFLICT DO NOTHING، بعد UPDATE، یک commit | دقیقاً یک اثر | یک insert اضافه برای هر پیام |
| دو worker، یک پیام | unique constraint + transaction کوتاه + lock_timeout | insert دوم منتظر میماند و ۰ ردیف گزارش میکند | ضد race | تکراری بلوکشده لحظهای connection را نگه میدارد |
| ایمیل/SMS تکراری | claim، perform با کلید، complete؛ یا بپذیرید | ردیف lease بهعلاوهٔ Idempotency-Key | تکرار محدود | provider باید کلید را بپذیرد |
| webhook تکراری از شخص ثالث | dedup روی id رویداد خودشان | inbox با کلید event_id ارائهدهنده | بدون تغییر در producer کار میکند | پنجره باید افق retry آنها را بپوشاند |
| رویداد تکراری و خارج از ترتیب در read model | upsert با version check | WHERE version < EXCLUDED.version | جدول لازم نیست | version قابلاعتماد میخواهد |
| رانش شمارنده | semantics مجموعه | post_likes(post_id, user_id) یکتا؛ ردیفها را بشمارید | idempotent طبیعی | هزینهٔ شمارش؛ با version materialize کنید |
| replay یک topic بعد از رفع باگ | نام consumer تازه، یا نوشتن idempotent | دامنهٔ dedup تازه | بازسازی امن | تکراریهای داخل خود replay هنوز idempotency طبیعی میخواهند |
| جدول inbox غولپیکر | پنجره از مسیرهای redelivery؛ partition بر اساس زمان پیام | بعد از پنجره DROP PARTITION | پاکسازی ارزان | partition key باید ویژگی پیام باشد |
| producer با دو id دوبار publish کرده | dedup با business key | کلید (consumer, 'pay_42:captured') | تکراری معنایی را میگیرد | تکرار قانونی به discriminator نیاز دارد |
| پیام poison که تا ابد retry میشود | به DLQ reject کنید، هرگز processed علامت نزنید | خطای handler، mark را rollback میکند؛ سیاست DLQ تعداد تلاش را محدود میکند | شکستها دیده میشوند | Dead-Letter Queue |
Retry و مدیریت خطا (Retries and failure handling)
inbox باعث میشود retry امن باشد، پس handler میتواند بلند شکست بخورد. برای هر خطا تصمیم بگیرید ack کنید، requeue کنید یا به dead-letter بفرستید.
| نتیجه | وضعیت inbox | اقدام روی broker | Retry؟ |
|---|---|---|---|
تکراری (0 rows) | mark موجود | Ack | نه |
| handler موفق، commit موفق | mark commit شده | Ack | نه |
خطای گذرا (deadlock 40P01، serialization 40001، قطع connection، 55P03) | rollback شده | بدون ack یا nack با requeue | بله، با backoff (Retry، Backoff و Delayed Delivery) |
| خطای دائمی (payload بد، قاعدهٔ کسبوکار) | rollback شده | reject بدون requeue به DLQ | نه |
| crash پیش از commit | rollback شده | broker دوباره تحویل میدهد | بله |
| crash بعد از commit، پیش از ack | mark commit شده | broker دوباره تحویل میدهد؛ مسیر تکراری ack میدهد | بله، جذب میشود |
قاعدهها: فقط بعد از commit ack بدهید؛ پیامی را که دائماً شکست خورده هرگز processed علامت نزنید؛ داخل handler و در حالی که transaction باز است کل پیام را retry نکنید؛ transaction را برای 40001/40P01 در یک retry محدود بپیچید. helper زیر در Go برای هر چیز گذرا error برمیگرداند تا حلقهٔ consumer nack کند؛ job لاراول از $tries و $backoff و DB::transaction($callback, $attempts) برای retry در deadlock استفاده میکند.
انتخاب رویکرد (Choosing an approach)
| بار کاری | پیشنهاد | تکنیک اضافه | دلیل |
|---|---|---|---|
| پول: واریز کیف پول، دفتر کل، پرداخت | inbox در transaction کسبوکاری | دفتر append-only با کلید message id؛ کلید idempotency پاییندستی | یک تکراری از یک جدول گرانتر است |
| read model وضعیت سفارش | upsert با version check | بازسازی از log | تکراری و بیترتیبی بدون جدول مدیریت میشود |
| search index / refresh کش | idempotency طبیعی (بازسازی از وضعیت) | ShouldBeUnique برای ادغام dispatchها (Laravel) | ارزان؛ تکراری بیضرر است |
| شمارنده، لایک، بازدید | جدول مجموعه (جفتهای یکتا) یا شمارش دورهای | شمارندهٔ تقریبی اگر قابلقبول است | +1 هرگز idempotent نیست |
| ایمیل/SMS | at-least-once با claim و lease، یا at-most-once | کلید provider اگر دارد | بر اساس پیامد کسبوکاری تکراری در برابر جاافتادن انتخاب کنید |
| webhook شخص ثالث | inbox با کلید id رویداد ارائهدهنده | پنجره برنامهٔ retry آنها را بپوشاند | producer را نمیتوانید عوض کنید |
| Kafka به دیتابیس با حجم خیلی زیاد | offset در همان transaction | نوشتن idempotent | یک ردیف برای هر پیام بیش از حد گران است |
| Kafka به Kafka | transactionهای Kafka (EOS) | consumerهای read committed | commit atomic سمت broker اینجا کار میکند |
| active-active چندمنطقهای | idempotency طبیعی، یک مالک برای هر key | CRDT برای شمارنده | unique constraint per-region است |
Go
Before
consumer در RabbitMQ که به موجودی اضافه میکند و بعد ack میدهد. crash میان UPDATE و ack، قطع شبکه پیش از رسیدن ack، یا timeout در consumer همه به همان redelivery میرسند و کیف پول دوباره شارژ میشود.
// Package main is the "before": a consumer that is only correct if every
// message arrives exactly once. Brokers do not promise that.
package main
import (
"context"
"database/sql"
"encoding/json"
"log"
amqp "github.com/rabbitmq/amqp091-go"
)
type credit struct {
WalletID string `json:"wallet_id"`
Amount int64 `json:"amount"`
}
// handle adds the amount to the balance and acks afterwards. If the process
// dies between the UPDATE and the ack, the broker redelivers the message and
// the wallet is credited a second time.
func handle(ctx context.Context, db *sql.DB, d amqp.Delivery) error {
var c credit
if err := json.Unmarshal(d.Body, &c); err != nil {
return d.Reject(false)
}
if _, err := db.ExecContext(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
c.Amount, c.WalletID); err != nil {
return d.Nack(false, true)
}
return d.Ack(false)
}
func main() {
// Wiring omitted: this snippet only shows the handler's shape.
log.Println("see handle()")
_ = handle
}After
helper مشترک pgx بالاتر آمده است (pginbox): transaction شروع کنید، INSERT ... ON CONFLICT DO NOTHING در processed_messages، RowsAffected را بررسی کنید، نوشتن کسبوکاری را روی همان pgx.Tx انجام دهید، commit کنید. صفر یعنی «تکراری»؛ فراخواننده باز هم ack میدهد تا broker redelivery را متوقف کند. نسخهٔ قابلحمل با database/sql برای driverهای دیگر:
// Package inbox implements the idempotent-consumer pattern: the id of a
// message is inserted into a processed_messages table in the SAME transaction
// as the business write, and the primary key rejects the second attempt.
//
// CREATE TABLE processed_messages (
// consumer text NOT NULL,
// message_id text NOT NULL,
// processed_at timestamptz NOT NULL DEFAULT now(),
// PRIMARY KEY (consumer, message_id)
// );
package inbox
import (
"context"
"database/sql"
"fmt"
)
// Handler performs the business write inside the transaction it is given.
type Handler func(ctx context.Context, tx *sql.Tx) error
// Process runs fn at most once per (consumer, messageID). It returns
// processed=false when the message was already handled; the caller should
// still acknowledge it so the broker stops redelivering.
func Process(ctx context.Context, db *sql.DB, consumer, messageID string, fn Handler) (processed bool, err error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return false, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }() // no-op after Commit
// Mark and process in one transaction: both happen or neither does.
res, err := tx.ExecContext(ctx,
`INSERT INTO processed_messages (consumer, message_id)
VALUES ($1, $2)
ON CONFLICT (consumer, message_id) DO NOTHING`,
consumer, messageID)
if err != nil {
return false, fmt.Errorf("mark: %w", err)
}
if n, err := res.RowsAffected(); err != nil {
return false, err
} else if n == 0 {
return false, nil // duplicate: roll back (nothing to undo) and skip
}
if err := fn(ctx, tx); err != nil {
return false, fmt.Errorf("handle: %w", err) // rollback also removes the mark
}
if err := tx.Commit(); err != nil {
return false, fmt.Errorf("commit: %w", err)
}
return true, nil
}برای اثرهای بیرون از دیتابیس، نسخهٔ claim/complete (TryClaim، Complete) یک lease نگه میدارد تا crash جبران شود، و فراخوانی HTTP کلید پاییندستی را حمل میکند:
package pginbox
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// Claim is for side effects that cannot join the database transaction (an
// email, an HTTP call). The inbox row becomes a small state machine:
//
// CREATE TABLE inbox_messages (
// consumer text NOT NULL,
// message_id text NOT NULL,
// status text NOT NULL CHECK (status IN ('processing', 'done')),
// lease_until timestamptz NOT NULL,
// attempts int NOT NULL DEFAULT 1,
// received_at timestamptz NOT NULL DEFAULT now(),
// PRIMARY KEY (consumer, message_id)
// );
//
// Claim -> perform the effect with a downstream idempotency key -> Complete.
// A crash between Claim and Complete is repaired by the lease: after it
// expires, the redelivered message may claim the row again and repeat the
// effect, which is safe only because the downstream deduplicates on the key.
type ClaimState int
const (
Acquired ClaimState = iota // you own the row: perform the effect
AlreadyDone // a previous attempt completed
InFlight // another worker holds a live lease
)
const claimSQL = `INSERT INTO inbox_messages (consumer, message_id, status, lease_until)
VALUES ($1, $2, 'processing', now() + make_interval(secs => $3))
ON CONFLICT (consumer, message_id) DO UPDATE
SET lease_until = EXCLUDED.lease_until,
attempts = inbox_messages.attempts + 1
WHERE inbox_messages.status = 'processing'
AND inbox_messages.lease_until < now()
RETURNING status`
// TryClaim inserts the row, or re-claims it when a previous lease expired.
func TryClaim(ctx context.Context, q interface {
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}, consumer, messageID string, lease time.Duration) (ClaimState, error) {
var status string
err := q.QueryRow(ctx, claimSQL, consumer, messageID, lease.Seconds()).Scan(&status)
if err == nil {
return Acquired, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return 0, fmt.Errorf("claim: %w", err)
}
// The WHERE clause rejected us: either done, or someone else's live lease.
err = q.QueryRow(ctx,
`SELECT status FROM inbox_messages WHERE consumer = $1 AND message_id = $2`,
consumer, messageID).Scan(&status)
if err != nil {
return 0, fmt.Errorf("claim status: %w", err)
}
if status == "done" {
return AlreadyDone, nil
}
return InFlight, nil
}
// Complete marks the effect as performed. Run it after the external call
// succeeded; if it fails, the lease expires and the effect is repeated with
// the same downstream idempotency key.
func Complete(ctx context.Context, q interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}, consumer, messageID string) error {
_, err := q.Exec(ctx,
`UPDATE inbox_messages SET status = 'done' WHERE consumer = $1 AND message_id = $2`,
consumer, messageID)
return err
}// Package main shows an idempotent consumer whose side effect is an HTTP
// call to another system (a mail provider, a payment gateway). The inbox
// cannot make that call atomic with the database, so the consumer claims the
// message, calls with a downstream idempotency key, then marks it done.
package main
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"academy/idempotent-consumer-inbox/after/pginbox"
)
const consumer = "welcome-email"
// sendEmail calls the provider. The Idempotency-Key header makes the call
// safe to repeat: a provider that supports it returns the first response.
func sendEmail(ctx context.Context, messageID string, body []byte) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
os.Getenv("MAIL_API_URL"), bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
// Derived from the message id, so every retry of THIS message repeats
// the same key and a new message gets a new one.
req.Header.Set("Idempotency-Key", consumer+":"+messageID)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err // timeout: outcome unknown, the retry is safe because of the key
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return fmt.Errorf("provider returned %d", resp.StatusCode)
}
return nil
}
// handle returns nil when the message may be acknowledged.
func handle(ctx context.Context, pool *pgxpool.Pool, messageID string, body []byte) error {
state, err := pginbox.TryClaim(ctx, pool, consumer, messageID, 2*time.Minute)
if err != nil {
return err
}
switch state {
case pginbox.AlreadyDone:
return nil // acknowledge: the email was sent
case pginbox.InFlight:
// Another worker holds a live lease. Do NOT acknowledge: if that
// worker dies, this redelivery repeats the effect after the lease.
return fmt.Errorf("message %s is in flight elsewhere", messageID)
}
if err := sendEmail(ctx, messageID, body); err != nil {
return err // lease expires, redelivery claims again
}
return pginbox.Complete(ctx, pool, consumer, messageID)
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL and MAIL_API_URL to run")
}
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// In real code this is called from the broker consumer loop.
if err := handle(context.Background(), pool, "msg-1", []byte(`{"to":"a@example.com"}`)); err != nil {
log.Println(err)
}
}پاکسازی و پنجرهٔ dedup:
// Package cleanup deletes dedup records that can no longer matter. A record
// only has to live as long as a duplicate can still arrive, so retention is
// derived from the longest redelivery path, not from a round number.
package cleanup
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// Window is the dedup window: the longest time between the first and the
// last possible delivery of the same message. Add every source of lateness:
// broker retention or visibility timeout, retry and backoff schedule, the
// longest DLQ parking time, and the producer's own retry horizon.
func Window(brokerRedelivery, retrySchedule, dlqParking, producerRetry, margin time.Duration) time.Duration {
return brokerRedelivery + retrySchedule + dlqParking + producerRetry + margin
}
// Prune deletes expired rows in small batches so that no single statement
// holds locks or generates WAL for long. It returns the number deleted.
func Prune(ctx context.Context, pool *pgxpool.Pool, window time.Duration, batch int) (int64, error) {
var total int64
for {
tag, err := pool.Exec(ctx, `
DELETE FROM processed_messages
WHERE (consumer, message_id) IN (
SELECT consumer, message_id
FROM processed_messages
WHERE processed_at < now() - make_interval(secs => $1)
ORDER BY processed_at
LIMIT $2
)`, window.Seconds(), batch)
if err != nil {
return total, err
}
total += tag.RowsAffected()
if tag.RowsAffected() < int64(batch) {
return total, nil
}
select {
case <-ctx.Done():
return total, ctx.Err()
case <-time.After(100 * time.Millisecond): // let autovacuum and replicas breathe
}
}
}تستی که همان پیام را دو بار replay میکند، با transaction جعلی تا دیتابیس لازم نباشد (اجرایش کردیم: ok):
package pginbox
import (
"context"
"errors"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// fakeDB mimics the one property the inbox relies on: a primary key that
// rejects a second committed (consumer, message_id), and a transaction whose
// inserts vanish on rollback. No PostgreSQL needed.
type fakeDB struct{ committed map[string]bool }
type fakeTx struct {
pgx.Tx // nil: any method the inbox does not use panics loudly
db *fakeDB
pending map[string]bool
}
func (d *fakeDB) Begin(context.Context) (pgx.Tx, error) {
return &fakeTx{db: d, pending: map[string]bool{}}, nil
}
func (t *fakeTx) Exec(_ context.Context, _ string, args ...any) (pgconn.CommandTag, error) {
key := args[0].(string) + "/" + args[1].(string)
if t.db.committed[key] || t.pending[key] {
return pgconn.NewCommandTag("INSERT 0 0"), nil // ON CONFLICT DO NOTHING
}
t.pending[key] = true
return pgconn.NewCommandTag("INSERT 0 1"), nil
}
func (t *fakeTx) Commit(context.Context) error {
for k := range t.pending {
t.db.committed[k] = true
}
return nil
}
func (t *fakeTx) Rollback(context.Context) error { return nil } // pending is dropped
func TestReplayTwiceRunsHandlerOnce(t *testing.T) {
db := &fakeDB{committed: map[string]bool{}}
calls := 0
fn := func(context.Context, pgx.Tx) error { calls++; return nil }
first, err := Process(context.Background(), db, "wallet-credit", "msg-1", fn)
if err != nil || first != Processed {
t.Fatalf("first delivery: %v, %v", first, err)
}
second, err := Process(context.Background(), db, "wallet-credit", "msg-1", fn)
if err != nil || second != Duplicate {
t.Fatalf("redelivery: %v, %v", second, err)
}
if calls != 1 {
t.Fatalf("handler ran %d times, want 1", calls)
}
}
func TestFailedHandlerRollsBackTheMark(t *testing.T) {
db := &fakeDB{committed: map[string]bool{}}
boom := errors.New("boom")
if _, err := Process(context.Background(), db, "c", "msg-2",
func(context.Context, pgx.Tx) error { return boom }); !errors.Is(err, boom) {
t.Fatalf("want boom, got %v", err)
}
// The mark was rolled back, so redelivery must run the handler again.
calls := 0
res, err := Process(context.Background(), db, "c", "msg-2",
func(context.Context, pgx.Tx) error { calls++; return nil })
if err != nil || res != Processed || calls != 1 {
t.Fatalf("retry: %v, %v, calls=%d", res, err, calls)
}
}
func TestSameIDDifferentConsumerBothRun(t *testing.T) {
db := &fakeDB{committed: map[string]bool{}}
calls := 0
fn := func(context.Context, pgx.Tx) error { calls++; return nil }
_, _ = Process(context.Background(), db, "billing", "msg-3", fn)
_, _ = Process(context.Background(), db, "shipping", "msg-3", fn)
if calls != 2 {
t.Fatalf("two consumers must each run once, got %d", calls)
}
}زاویهٔ Go
database/sql نوع خطای «unique violation» قابلحمل ندارد؛ برای همین helper از ON CONFLICT DO NOTHING استفاده میکند و ردیف میشمارد بهجای اینکه خطای driver را parse کند؛ با pgx شکل صریحتر errors.As(err, &pgErr) روی *pgconn.PgError و pgErr.Code == "23505" است، و در MySQL driver خطای ER_DUP_ENTRY (۱۰۶۲) میدهد. شکل transaction همان idiom معمول است: Begin، defer tx.Rollback(ctx)، Commit، مثل هر نوشتن atomic دیگر. تصمیم چه زمانی ack بدهیم در حلقهٔ consumer میماند، بیرون از helper: بعد از برگشت Process ack بدهید، چه processed گزارش کرده باشد چه duplicate، و فقط روی error، nack کنید. interface به نام Beginner (که *pgxpool.Pool برآورده میکند) چیزی است که جعلیسازی در تست را ممکن کرده. تأیید پیام را ببینید.
Laravel
Before
job صفشدهای که increment() صدا میزند. workerهای لاراول at-least-once میدهند: jobی که timeout میشود یا workerش بعد از UPDATE کشته میشود آزاد میشود و دوباره اجرا میشود. مستندات صف تنظیماتش را توضیح میدهند: retry_after و --timeout "work together to ensure that jobs are not lost and that jobs are only successfully processed once"، و --timeout باید کوتاهتر از retry_after باشد؛ وگرنه job هنوز-در-حال-اجرا را worker دوم retry میکند.
<?php
namespace App\Jobs;
use App\Models\Wallet;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
// Only correct if the queue delivers this job exactly once. A worker that
// dies after the UPDATE but before the job is deleted (or a retry after a
// timeout) credits the wallet again.
class CreditWallet implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public int $walletId,
public int $amount,
) {}
public function handle(): void
{
$wallet = Wallet::findOrFail($this->walletId);
// balance = balance + N, executed on every delivery.
$wallet->increment('balance', $this->amount);
}
}After
جدول processed_messages که primary keyاش (consumer, message_id) است، و یک DB::transaction که اول insertOrIgnore میزند. query builder مستند کرده که insertOrIgnore خطاها را هنگام insert نادیده میگیرد، و تعداد ردیف برگشتی میگوید ردیف تازه بوده یا نه. message id آرگومان constructor است که producer میسازد، پس هر retry از job serializeشده همان مقدار را حمل میکند.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// The inbox table. The composite primary key is the dedup primitive: the
// database rejects a second (consumer, message_id) even when two workers race.
return new class extends Migration
{
public function up(): void
{
Schema::create('processed_messages', function (Blueprint $table) {
$table->string('consumer', 100);
$table->string('message_id', 200);
$table->timestampTz('processed_at')->useCurrent()->index(); // for the cleanup job
$table->primary(['consumer', 'message_id']);
});
// For effects that cannot join the transaction (email, HTTP): the row
// is a small state machine, see SendWelcomeEmail.php.
Schema::create('inbox_messages', function (Blueprint $table) {
$table->string('consumer', 100);
$table->string('message_id', 200);
$table->string('status', 20); // processing | done
$table->timestampTz('lease_until');
$table->unsignedInteger('attempts')->default(1);
$table->timestampTz('received_at')->useCurrent();
$table->primary(['consumer', 'message_id']);
});
}
public function down(): void
{
Schema::dropIfExists('inbox_messages');
Schema::dropIfExists('processed_messages');
}
};<?php
namespace App\Jobs;
use App\Models\Wallet;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
// Migration (once):
//
// Schema::create('processed_messages', function (Blueprint $table) {
// $table->string('consumer');
// $table->string('message_id');
// $table->timestamp('processed_at')->useCurrent()->index(); // for cleanup
// $table->primary(['consumer', 'message_id']);
// });
class CreditWallet implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public int $walletId,
public int $amount,
// Generated once by the producer, e.g. (string) Str::uuid(), and
// carried inside the payload so every redelivery has the same value.
public string $messageId,
) {}
public function handle(): void
{
DB::transaction(function () {
// insertOrIgnore returns the number of rows inserted: 0 means the
// primary key already holds this (consumer, message_id).
$inserted = DB::table('processed_messages')->insertOrIgnore([
'consumer' => 'wallet-credit',
'message_id' => $this->messageId,
]);
if ($inserted === 0) {
return; // duplicate: acknowledge by returning normally
}
// Same transaction as the mark: both commit or neither does.
Wallet::whereKey($this->walletId)->increment('balance', $this->amount);
});
}
}insertOrIgnore یک هشدار دارد که مستندات صریح گفتهاند: خطاهای duplicate-key را نادیده میگیرد و "other types of errors may also be ignored depending on the database engine". اگر خطاها بلند شنیده شوند را ترجیح میدهید، insert ساده بزنید و UniqueConstraintViolationException را بگیرید، که زیرکلاس QueryException در Illuminate\Database است. catch باید بیرون از transaction باشد، چون در PostgreSQL statement ناموفق transaction را abort میکند.
<?php
namespace App\Support;
use Closure;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
// The same inbox, written with a plain insert and the unique-violation
// exception instead of insertOrIgnore. Use this form when you want other
// database errors to surface instead of being swallowed.
final class Inbox
{
/**
* Run $work at most once per ($consumer, $messageId).
* Returns true when it ran, false when the message was a duplicate.
*/
public static function once(string $consumer, string $messageId, Closure $work): bool
{
try {
DB::transaction(function () use ($consumer, $messageId, $work) {
DB::table('processed_messages')->insert([
'consumer' => $consumer,
'message_id' => $messageId,
]);
$work();
});
} catch (UniqueConstraintViolationException) {
// Caution: on PostgreSQL a violation aborts the surrounding
// transaction, which is why the catch sits OUTSIDE it.
return false;
}
return true;
}
}برای اینکه هر jobی را بدون دستزدن به handle() idempotent کنید، آن را در یک job middleware بپیچید که $next($job) را داخل inbox اجرا میکند. اگر $messageId تولیدکننده باشد از آن استفاده میکند، وگرنه از uuid در payload صف که لاراول هنگام dispatch مینویسد ($this->job->uuid()):
<?php
namespace App\Jobs\Middleware;
use App\Support\Inbox;
use Closure;
// A job middleware that turns any job into an idempotent consumer: the job's
// handle() runs inside the inbox transaction, once per (consumer, message id).
//
// Which id? Prefer one the PRODUCER chose and put on the job (a public
// $messageId property). Fall back to the queue payload's uuid, which Laravel
// writes when the job is dispatched and which survives retries and releases
// of that one dispatch. It does not catch a producer that dispatches the same
// logical event twice; only a business id does.
class OncePerMessage
{
public function __construct(private string $consumer) {}
public function handle(object $job, Closure $next): void
{
$id = $job->messageId ?? $job->job?->uuid();
if ($id === null || $id === '') {
// No identity means no dedup. Fail loudly instead of double-applying.
throw new \LogicException('OncePerMessage needs a messageId or a queue uuid');
}
Inbox::once($this->consumer, (string) $id, fn () => $next($job));
}
}<?php
namespace App\Jobs;
use App\Jobs\Middleware\OncePerMessage;
use App\Models\Wallet;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
// The handler stays plain; idempotency is the middleware's job.
class CreditWalletOnce implements ShouldQueue
{
use Queueable;
public function __construct(
public int $walletId,
public int $amount,
public string $messageId, // generated once by the producer
) {}
/** @return array<int, object> */
public function middleware(): array
{
return [new OncePerMessage('wallet-credit')];
}
public function handle(): void
{
// Runs inside the inbox transaction: mark + increment commit together.
Wallet::whereKey($this->walletId)->increment('balance', $this->amount);
}
}idempotency طبیعی در query builder: update به یک مقدار، upsert با key، و update شرطی با where('status', 'pending').
<?php
namespace App\Jobs;
use App\Models\Wallet;
use Illuminate\Support\Facades\DB;
// Natural idempotency: operations whose repetition changes nothing.
final class Natural
{
public static function examples(int $walletId, string $orderId): void
{
// Set, do not increment: running it twice leaves the same row.
Wallet::whereKey($walletId)->update(['status' => 'frozen']);
// Upsert keyed on a business key.
DB::table('order_projection')->upsert(
[['order_id' => $orderId, 'status' => 'paid']],
['order_id'],
['status'],
);
// Conditional update: only moves forward once.
DB::table('orders')
->where('id', $orderId)
->where('status', 'pending')
->update(['status' => 'paid']);
}
}اثر بیرونی با lease و کلید پاییندستی، و پاکسازی زمانبندیشده:
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
// The side effect (an HTTP call) cannot join the database transaction, so the
// inbox row becomes claim -> perform -> complete, and the call carries a
// downstream Idempotency-Key. If the worker dies between the call and
// complete(), the lease expires, the redelivered job claims the row again and
// repeats the call; the provider returns the first result for the same key.
class SendWelcomeEmail implements ShouldQueue
{
use Queueable;
public function __construct(
public string $userId,
public string $messageId, // chosen once by the producer
) {}
public function handle(): void
{
$consumer = 'welcome-email';
// Insert the claim, or re-claim it when a previous lease expired.
$claimed = DB::select(
"INSERT INTO inbox_messages (consumer, message_id, status, lease_until)
VALUES (?, ?, 'processing', now() + make_interval(secs => ?))
ON CONFLICT (consumer, message_id) DO UPDATE
SET lease_until = EXCLUDED.lease_until,
attempts = inbox_messages.attempts + 1
WHERE inbox_messages.status = 'processing'
AND inbox_messages.lease_until < now()
RETURNING status",
[$consumer, $this->messageId, 120],
);
if ($claimed === []) {
$status = DB::table('inbox_messages')
->where('consumer', $consumer)
->where('message_id', $this->messageId)
->value('status');
if ($status === 'done') {
return; // already sent: acknowledge by returning
}
// A live lease belongs to another worker: release and retry later.
$this->release(30);
return;
}
Http::withHeaders(['Idempotency-Key' => $consumer.':'.$this->messageId])
->timeout(10)
->post(config('services.mail.url'), ['user_id' => $this->userId])
->throw(); // non-2xx throws: the job is retried after the lease
DB::table('inbox_messages')
->where('consumer', $consumer)
->where('message_id', $this->messageId)
->update(['status' => 'done']);
}
}<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
// Deletes inbox rows older than the dedup window, in small batches so that no
// single statement holds locks or produces a huge WAL burst. PostgreSQL's
// DELETE has no LIMIT, hence the ctid sub-select.
//
// Schedule it (routes/console.php):
// Schedule::command('inbox:prune --days=14')->hourly()->onOneServer();
class PruneProcessedMessages extends Command
{
protected $signature = 'inbox:prune {--days=14} {--batch=5000}';
protected $description = 'Delete processed_messages rows older than the dedup window';
public function handle(): int
{
$batch = (int) $this->option('batch');
$cutoff = now()->subDays((int) $this->option('days'));
$total = 0;
do {
$deleted = DB::delete(
'DELETE FROM processed_messages WHERE ctid IN (
SELECT ctid FROM processed_messages
WHERE processed_at < ? ORDER BY processed_at LIMIT ?
)',
[$cutoff, $batch],
);
$total += $deleted;
usleep(100_000); // let autovacuum and replicas breathe
} while ($deleted === $batch);
$this->info("pruned {$total} rows older than {$cutoff}");
return self::SUCCESS;
}
}و تستی که هر consumer لازم دارد، همان پیام را دو بار تحویل بدهید (برای PHPUnit با RefreshDatabase نوشته شده؛ syntax بررسی شده ولی اجرا نشده چون اینجا اپ Laravel نداریم):
<?php
namespace Tests\Feature;
use App\Jobs\CreditWalletOnce;
use App\Models\Wallet;
use App\Support\Inbox;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
// The one test every consumer needs: deliver the same message twice and
// assert the effect happened once. dispatch_sync runs handle() in-process,
// the way a redelivery would run it on a worker.
class ReplayTwiceTest extends TestCase
{
use RefreshDatabase;
public function test_a_redelivered_message_is_applied_once(): void
{
$wallet = Wallet::factory()->create(['balance' => 0]);
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-1');
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-1'); // the duplicate
$this->assertSame(500, $wallet->fresh()->balance);
$this->assertDatabaseCount('processed_messages', 1);
}
public function test_different_messages_are_both_applied(): void
{
$wallet = Wallet::factory()->create(['balance' => 0]);
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-1');
CreditWalletOnce::dispatchSync($wallet->id, 500, 'msg-2');
$this->assertSame(1000, $wallet->fresh()->balance);
}
public function test_a_failing_handler_does_not_leave_a_mark(): void
{
try {
Inbox::once('wallet-credit', 'msg-3', function () {
throw new \RuntimeException('boom'); // fails after the mark was inserted
});
} catch (\RuntimeException) {
// expected: the broker would redeliver the message
}
// The transaction rolled back, so the redelivery is allowed to run.
$this->assertDatabaseMissing('processed_messages', ['message_id' => 'msg-3']);
$this->assertTrue(Inbox::once('wallet-credit', 'msg-3', fn () => null));
}
}زاویهٔ Laravel
ShouldBeUnique یک inbox نیست. مستندات صف Laravel 13 آن را اینطور توصیف میکنند: "only one instance of a specific job is on the queue at any point in time"، با گرفتن قفل cache روی uniqueId که وقتی job "completes processing or fails all of its retry attempts" آزاد میشود (یا بعد از #[UniqueFor] ثانیه). جلوی dispatch تکراری jobهای معادل را میگیرد. به cache driver با قفل atomic نیاز دارد، روی jobهای داخل batch اعمال نمیشود، و handle() را در برابر redelivery یک job محافظت نمیکند. در کد فریمورک (Illuminate\Bus\UniqueLock) عمر قفل uniqueFor یا ۰ است و عمر ۰ یعنی بدون انقضا؛ crashی که آزادسازی را رد کند قفل را تا پاککردن دستی باقی میگذارد، پس همیشه #[UniqueFor] بگذارید. ShouldBeUniqueUntilProcessing قفل را وقتی پردازش شروع میشود آزاد میکند، که اجازه میدهد نسخهٔ دوم در حالی dispatch شود که اولی هنوز اجراست: باز هم ضعیفتر. برای «این index را تازه کن، یکییکی» مناسب است؛ برای موجودی از inbox استفاده کنید.
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
// ShouldBeUnique stops a second copy from being DISPATCHED while the first is
// queued or running (it takes a cache lock on uniqueId()). It does not make
// handle() safe against redelivery after the lock is released, and the lock
// lives in the cache, not in your database transaction. Use it for "refresh
// this thing, one at a time", never for money.
#[UniqueFor(3600)] // seconds until the lock is released even if the job never finishes
class RefreshSearchIndex implements ShouldQueue, ShouldBeUnique
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(public int $productId) {}
public function uniqueId(): string
{
return (string) $this->productId;
}
public function handle(): void
{
// Naturally idempotent: rebuilds the document from current state.
}
}WithoutOverlapping هم inbox نیست. Illuminate\Queue\Middleware\WithoutOverlapping فقط وقتی handle() اجراست یک قفل atomic cache نگه میدارد ($next($job) داخل try و release() در finally)، پس دو job با همان key هرگز همزمان اجرا نمیشوند، ولی redelivery بعد از پایان اولی عادی اجرا میشود. مستندات هشدار میدهند رهاسازی jobِ همپوشان "will still increment the job's total number of attempts"، پس Tries و MaxExceptions را تنظیم کنید؛ releaseAfter() آن را دوباره صف میکند، dontRelease() حذفش میکند، expireAfter() قفل مانده از worker مرده را آزاد میکند. از آن برای سریالکردن بهازای هر key استفاده کنید، و وقتی هر دو را میخواهید با inbox ترکیب کنید:
<?php
namespace App\Jobs;
use App\Jobs\Middleware\OncePerMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Middleware\WithoutOverlapping;
// WithoutOverlapping answers "never two of these at the same time for this
// key". It does NOT answer "never twice". It holds an atomic cache lock only
// while handle() runs; once released, a redelivery runs normally. Combine it
// with the inbox when you need both: serialise per wallet, dedup per message.
class SerializedPerWallet implements ShouldQueue
{
use Queueable;
public int $tries = 5; // releasing an overlapping job still counts as an attempt
public function __construct(
public int $walletId,
public int $amount,
public string $messageId,
) {}
/** @return array<int, object> */
public function middleware(): array
{
return [
(new WithoutOverlapping((string) $this->walletId))
->releaseAfter(10) // put the job back and retry in 10 s
->expireAfter(180), // free the lock even if the worker died
new OncePerMessage('wallet-credit'),
];
}
public function handle(): void
{
// ...business write; safe against both overlap and redelivery
}
}Transaction و dispatch. jobی که داخل transaction dispatch شود ممکن است پیش از commit برداشته شود؛ مستندات صف after_commit روی connection یا ->afterCommit() روی هر dispatch را پیشنهاد میکنند. این «job پیش از وجود ردیف اجرا میشود» را حل میکند، نه تکراری را. HTTP. یک middleware میتواند Idempotency-Key را با Cache::add (atomic) claim کند، در retry پاسخ ذخیرهشده را replay کند، تا وقتی درخواست اول در جریان است 409 و برای payload متفاوت 422 بدهد، مثل همتای HTTP. پیشنویس header را بهصورت structured-field string در نقلقول تایپ میکند؛ middleware آن را مقدار opaque میبیند.
تفاوتهای اجرا در brokerها (Broker differences)
هر broker چه چیزی برای ساختن کلید در اختیارتان میگذارد، خودش چه کاری میکند، و چه کاری نه.
| قابلیت | RabbitMQ | Kafka | Redis Streams |
|---|---|---|---|
| شناسهٔ انتخابشده توسط producer | property به نام message-id | header یا فیلد payload | فیلد entry؛ IDMP iid (نسخهٔ 8.6 به بعد) |
| شناسهٔ ساختهشده توسط broker | قابلاستفاده ندارد (delivery tag مخصوص channel است) | topic-partition-offset | entry id به شکل ms-seq |
| dedup سمت broker | ندارد | idempotent producer، در session همان producer | IDMP / IDMPAUTO (نسخهٔ 8.6 به بعد، با پنجره) |
| نشانهٔ redelivery | flag به نام redelivered (وقتی ست باشد فقط hint) | ندارد: فقط موقعیت commitشدهٔ خودتان | شمارندهٔ تحویل در XPENDING |
| موقعیت consumer | ack برای هر پیام | offset برای هر partition | XACK برای هر entry (همان PEL) |
| محرک redelivery | بستهشدن channel با پیامهای unacked، basic.nack/reject با requeue | rebalance، crash پیش از commit، برگشت offset | pending entry بیکار که XCLAIM/XAUTOCLAIM شود، یا XREADGROUP با id برابر 0 |
| چه چیزی dedup را میشکند | message-id خالی | کلیدی که فقط coordinates است؛ ارسال دوبارهٔ producer | retry در XADD بدون IDMP |
NATS JetStream، SQS FIFO، Azure Service Bus و Pulsar هرکدام پنجرهٔ dedup سمت producer مخصوص خود را دارند (به جدول TTL نگاه کنید)؛ Brokerهای دیگر آنها را میپوشاند.
RabbitMQ
AMQP 0-9-1 یک property به نام message-id تعریف میکند؛ راهنمای publishers در RabbitMQ آن را "Message ID" با توضیح "Arbitrary message ID" فهرست میکند، اختیاری است، و broker هرگز آن را نمیسازد، تفسیر نمیکند یا چک نمیکند، پس dedup کاملاً کار consumer است و producer باید آن را پر کند (در amqp091-go، Publishing.MessageId که بهصورت Delivery.MessageId خوانده میشود). consumer یک flag به نام redelivered هم میگیرد. راهنمای reliability دقیق است: وقتی ست است، "this is a hint that a consumer may have seen this message before. This is not guaranteed as the original delivery might have not made it to any consumers"؛ وقتی ست نیست، "it is guaranteed that the message has not been seen before". پس consumerی که dedup برایش گران است "can do this only for messages with the redelivered flag set". این بهینهسازی فقط در برابر redelivery سمت broker امن است: producerی که بعد از گمشدن confirm دوباره publish کرده پیام تازهای میسازد که redelivered ندارد؛ اگر محافظت در برابر تکراری producer میخواهید روی هر پیام از inbox استفاده کنید. quorum queueها requeueها را به delivery limit صف میشمارند، که حلقهٔ requeue را محدود میکند. پکیج لاراول vladimir-yuldashev/laravel-queue-rabbitmq property به نام correlation_id در AMQP را از id در payload job میسازد (متد createMessage() را در کدش خواندیم) و message-id را تا جایی که یافتیم در دسترس نمیگذارد؛ پس در Laravel روی $messageId خودتان یا uuid در payload dedup کنید.
// Package main consumes from RabbitMQ and dedups on the AMQP message-id
// property, which the publisher must set. The redelivered flag is only logged.
package main
import (
"context"
"encoding/json"
"log"
"os"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"academy/idempotent-consumer-inbox/after/pginbox"
)
type credit struct {
WalletID string `json:"wallet_id"`
Amount int64 `json:"amount"`
}
func handle(ctx context.Context, pool *pgxpool.Pool, d amqp.Delivery) error {
if d.MessageId == "" {
// No id means no dedup; refuse rather than silently double-apply.
return d.Reject(false) // dead-letters when the queue has a DLX
}
if d.Redelivered {
// A hint, never a verdict: "delivered before" is not "processed before".
log.Printf("redelivery of %s: relying on the inbox", d.MessageId)
}
var c credit
if err := json.Unmarshal(d.Body, &c); err != nil {
return d.Reject(false)
}
res, err := pginbox.Process(ctx, pool, "wallet-credit", d.MessageId,
func(ctx context.Context, tx pgx.Tx) error {
_, err := tx.Exec(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
c.Amount, c.WalletID)
return err
})
if err != nil {
return d.Nack(false, true) // transient: requeue and try again
}
log.Printf("%s: %s", d.MessageId, res)
// Ack both for "processed" and for "already processed".
return d.Ack(false)
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
if err := ch.Qos(10, 0, false); err != nil {
log.Fatal(err)
}
deliveries, err := ch.Consume("wallet.credits", "", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range deliveries {
if err := handle(context.Background(), pool, d); err != nil {
log.Println("ack/nack failed:", err)
}
}
}Kafka
idempotent producer در Kafka فقط قابلیت سمت broker است. مستندات طراحی میگوید از 0.11.0.0 "guarantees that resending will not result in duplicate entries in the log" با producer id و شمارهٔ sequence، و Javadoc مربوط به producer یادآوری میکند از Kafka 3.0 پیشفرض است (enable.idempotence=true، acks=all) و idempotence را فقط "within a single session" تضمین میکند. این تکراریهای ناشی از retry در producer را حذف میکند. برای consumerی که recordی را پردازش میکند، پیش از commit offset میمیرد، و بعد از rebalance دوباره همان record را میخواند هیچ کاری نمیکند، و کمکی هم نمیکند اگر برنامهٔ شما همان رویداد را از دو مسیر کد publish کند.
exactly-once کافکا (consume-transform-produce) یک inbox نیست. با transactional.id روی producer و isolation.level=read_committed و enable.auto.commit=false روی consumer، offsetهای consumer در همان transaction کافکا که recordهای خروجی را مینویسد نوشته میشوند (sendOffsetsToTransaction؛ GroupTransactSession در franz-go شروع و پایان را برایتان انجام میدهد). اگر transaction abort شود، هم خروجی و هم offsetها برمیگردند. این برای Kafka-به-Kafka درست است. مستندات طراحی حدش را میگوید: "Exactly-once delivery for other destination systems generally requires cooperation with such systems". نوشتن در دیتابیس داخل آن حلقه بیرون از transaction کافکاست، پس هنوز inbox لازم دارید، یا offset کنار خروجی.
record شناسهٔ خودش را ندارد، پس گزینهها header برنامهای (message-id که producer مینویسد) یا coordinates به شکل topic-partition-offset است. coordinates پایدار است و همکاری producer نمیخواهد، ولی دو نسخهٔ نوشتهشده در offsetهای متفاوت را dedup نمیکند، و اگر topic دوباره ساخته یا به cluster دیگر mirror شود عوض میشود. offset را فقط بعد از transaction inbox commit کنید (DisableAutoCommit)؛ تأیید پیام را ببینید.
// Package main consumes from Kafka with franz-go and dedups on a producer
// supplied "message-id" header, falling back to topic-partition-offset.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/twmb/franz-go/pkg/kgo"
"academy/idempotent-consumer-inbox/after/pginbox"
)
type credit struct {
WalletID string `json:"wallet_id"`
Amount int64 `json:"amount"`
}
// messageID prefers an id the producer put in a header: it survives producer
// retries that wrote the same event at two offsets. The coordinates are only
// stable per log position, so they catch redelivery after a rebalance but not
// a duplicate produced upstream.
func messageID(r *kgo.Record) string {
for _, h := range r.Headers {
if h.Key == "message-id" {
return string(h.Value)
}
}
return fmt.Sprintf("%s-%d-%d", r.Topic, r.Partition, r.Offset)
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
cl, err := kgo.NewClient(
kgo.SeedBrokers("localhost:9092"),
kgo.ConsumerGroup("wallet-credit"),
kgo.ConsumeTopics("wallet.credits"),
kgo.DisableAutoCommit(), // commit only after the inbox transaction
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
for {
fetches := cl.PollFetches(ctx)
if fetches.IsClientClosed() {
return
}
fetches.EachRecord(func(r *kgo.Record) {
var c credit
if err := json.Unmarshal(r.Value, &c); err != nil {
return // poison message: route to a DLQ in real code
}
_, err := pginbox.Process(ctx, pool, "wallet-credit", messageID(r),
func(ctx context.Context, tx pgx.Tx) error {
_, err := tx.Exec(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
c.Amount, c.WalletID)
return err
})
if err != nil {
log.Println("will be redelivered:", err)
return
}
// A crash before this commit only causes a redelivery,
// which the inbox turns into a no-op.
if err := cl.CommitRecords(ctx, r); err != nil {
log.Println("commit:", err)
}
})
}
}// Package main is Kafka's exactly-once consume-transform-produce loop with
// franz-go. It is correct for Kafka -> Kafka only: the output topic and the
// consumer offsets commit in one Kafka transaction. A database write inside
// the loop is NOT part of that transaction, so this is not an inbox.
package main
import (
"context"
"log"
"github.com/twmb/franz-go/pkg/kgo"
)
func main() {
sess, err := kgo.NewGroupTransactSession(
kgo.SeedBrokers("localhost:9092"),
kgo.TransactionalID("wallet-enricher-1"), // stable per instance
kgo.ConsumerGroup("wallet-enricher"),
kgo.ConsumeTopics("wallet.credits"),
kgo.FetchIsolationLevel(kgo.ReadCommitted()),
kgo.RequireStableFetchOffsets(),
)
if err != nil {
log.Fatal(err)
}
defer sess.Close()
ctx := context.Background()
for {
fetches := sess.PollFetches(ctx)
if fetches.IsClientClosed() {
return
}
if err := sess.Begin(); err != nil {
log.Fatal(err)
}
fetches.EachRecord(func(r *kgo.Record) {
// Transform, then produce INSIDE the transaction. Writing to
// PostgreSQL here would still be at-least-once.
out := &kgo.Record{Topic: "wallet.credits.enriched", Key: r.Key, Value: r.Value}
sess.Produce(ctx, out, func(_ *kgo.Record, err error) {
if err != nil {
log.Println("produce:", err)
}
})
})
// Commits the produced records and the consumed offsets together,
// or aborts both (also when a rebalance happened meanwhile).
if _, err := sess.End(ctx, kgo.TryCommit); err != nil {
log.Println("end:", err)
}
}
}در Laravel با mateusjunges/laravel-kafka، handler یک ConsumerMessage با getHeaders()، getTopicName()، getPartition() و getOffset() میگیرد، که همان مواد خاماند.
<?php
namespace App\Kafka;
use App\Support\Inbox;
use Illuminate\Support\Facades\DB;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
// Registered with: Kafka::consumer(['wallet.credits'])->withHandler(new CreditHandler)
// (mateusjunges/laravel-kafka; getHeaders/getTopicName/getPartition/getOffset
// are listed on its "Message handlers" page).
class CreditHandler
{
public function __invoke(ConsumerMessage $message, MessageConsumer $consumer): void
{
$headers = $message->getHeaders() ?? [];
// Prefer an id the producer put in a header; the log coordinates only
// catch redelivery of the same record, not a duplicate produced twice.
$id = $headers['message-id']
?? sprintf('%s-%d-%d', $message->getTopicName(), $message->getPartition(), $message->getOffset());
$body = $message->getBody();
Inbox::once('wallet-credit', (string) $id, function () use ($body) {
DB::table('wallets')
->where('id', $body['wallet_id'])
->increment('balance', $body['amount']);
});
}
}Redis Streams
Redis برای هر entry در stream شناسهٔ یکتا میسازد (ms-seq از XADD). consumer group هر entry را به یک consumer میدهد و تا XACK آن را در لیست pending entries (PEL) نگه میدارد؛ entryای که consumerش مرده با XCLAIM یا XAUTOCLAIM بعد از حداقل زمان idle برداشته و با همان entry id دوباره تحویل میشود، و شمارندهٔ تحویل در XPENDING بالا میرود. پس entry id برای redelivery کلید dedup پایداری است. برای retry تولیدکننده پایدار نیست: اگر XADD timeout شد و producer دوباره فرستاد، دو entry با دو id داریم.
Redis 8.6 ایدمپوتنسی سمت producer را به XADD اضافه کرد (مستندات آن را "at-most-once production" مینامند): XADD stream IDMP producer-id idempotent-id * ... (یا IDMPAUTO producer-id که Redis محتوا را hash میکند). اگر همان producer-id و idempotent-id قبلاً استفاده شده باشد، فرمان "returns the ID of the original entry instead of creating a duplicate". پنجره per-stream است (XCFGSET stream IDMP-DURATION s IDMP-MAXSIZE n، پیشفرضها ۱۰۰ ثانیه و ۱۰۰ id برای هر producer) و producer باید بعد از restart همان pid را استفاده کند. این entryهای تکراری را حذف میکند، نه تحویلهای تکراریِ یک entry: consumerها هنوز inbox میخواهند. driver صف redis در لاراول از stream استفاده نمیکند، پس consumer مستقیماً از facade به نام Redis استفاده میکند.
// Package main reads a Redis Stream consumer group with go-redis, reclaims
// entries abandoned by dead consumers with XAUTOCLAIM, and dedups on a
// producer-supplied event_id (falling back to the entry id).
package main
import (
"context"
"errors"
"log"
"os"
"strconv"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"academy/idempotent-consumer-inbox/after/pginbox"
)
const (
stream = "wallet.credits"
group = "wallet-credit"
)
func handle(ctx context.Context, rdb *redis.Client, pool *pgxpool.Pool, m redis.XMessage) {
// m.ID is assigned by XADD, so it identifies a log entry, not an event.
// If the producer retried XADD there are two entries; prefer an id the
// producer put in the fields.
id := m.ID
if v, ok := m.Values["event_id"].(string); ok && v != "" {
id = v
}
walletID, _ := m.Values["wallet_id"].(string)
amount, _ := m.Values["amount"].(string)
n, err := strconv.ParseInt(amount, 10, 64)
if err != nil {
return // poison entry: park it, do not loop forever
}
_, err = pginbox.Process(ctx, pool, group, id,
func(ctx context.Context, tx pgx.Tx) error {
_, err := tx.Exec(ctx,
`UPDATE wallets SET balance = balance + $1 WHERE id = $2`,
n, walletID)
return err
})
if err != nil {
log.Println("left in the PEL for retry:", err)
return
}
if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
log.Println("xack:", err) // the entry is redelivered; the inbox absorbs it
}
}
// reclaim takes over entries idle in the pending list for over a minute
// (their consumer died). They arrive again with the SAME entry id.
func reclaim(ctx context.Context, rdb *redis.Client, pool *pgxpool.Pool) {
start := "0-0"
for {
msgs, next, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: stream, Group: group, Consumer: "worker-1",
MinIdle: time.Minute, Start: start, Count: 50,
}).Result()
if err != nil {
log.Println("xautoclaim:", err)
return
}
for _, m := range msgs {
handle(ctx, rdb, pool, m)
}
if next == "0-0" {
return
}
start = next
}
}
func main() {
if os.Getenv("DATABASE_URL") == "" {
log.Fatal("set DATABASE_URL to run")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer pool.Close()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
for {
reclaim(ctx, rdb, pool)
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: group, Consumer: "worker-1",
Streams: []string{stream, ">"}, Count: 10, Block: 5 * time.Second,
}).Result()
if err != nil {
if !errors.Is(err, redis.Nil) {
log.Println("read:", err)
}
continue
}
for _, s := range res {
for _, m := range s.Messages {
handle(ctx, rdb, pool, m)
}
}
}
}// Package main shows producer-side deduplication in Redis 8.6+: XADD with
// IDMP (a producer id plus an idempotent id the producer chooses). Resending
// the same pair is ignored while it is inside the stream's IDMP window.
package main
import (
"context"
"log"
"github.com/redis/go-redis/v9"
)
func main() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
// Window: keep each iid for 300 s, at most 1000 per producer.
// (XCFGSET stream IDMP-DURATION 300 IDMP-MAXSIZE 1000)
if err := rdb.Do(ctx, "XCFGSET", "wallet.credits",
"IDMP-DURATION", 300, "IDMP-MAXSIZE", 1000).Err(); err != nil {
log.Println("xcfgset:", err)
}
add := func() (string, error) {
return rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "wallet.credits",
ProducerID: "billing-1", // must be stable across restarts
IdempotentID: "payment-42", // reuse the SAME id when retrying
Values: map[string]any{"wallet_id": "w-7", "amount": 500, "event_id": "payment-42"},
}).Result()
}
first, err := add()
if err != nil {
log.Fatal(err)
}
second, err := add() // the retry after a lost reply
if err != nil {
log.Fatal(err)
}
log.Println("first:", first, "retry:", second) // expected: same entry id
}<?php
namespace App\Console\Commands;
use App\Support\Inbox;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
// Laravel's redis queue driver does not use streams, so this goes through the
// Redis facade. The calls below are the phpredis signatures
// (xReadGroup/xAck); Predis uses different argument shapes.
class ConsumeCredits extends Command
{
protected $signature = 'credits:consume';
public function handle(): void
{
$stream = 'wallet.credits';
$group = 'wallet-credit';
while (true) {
$batch = Redis::xReadGroup($group, 'worker-1', [$stream => '>'], 10, 5000);
foreach ($batch[$stream] ?? [] as $entryId => $fields) {
// The entry id names a log entry; an event_id field names the event.
$id = $fields['event_id'] ?? $entryId;
Inbox::once($group, $id, function () use ($fields) {
DB::table('wallets')
->where('id', $fields['wallet_id'])
->increment('balance', (int) $fields['amount']);
});
// Ack after the transaction committed; a crash before this line
// leaves the entry pending and the inbox absorbs the redelivery.
Redis::xAck($stream, $group, [$entryId]);
}
}
}
}در سیستمهای واقعی
- Eventuate در صفحهٔ الگوی Richardson نام برده شده: "The Eventuate framework implements this pattern."
- یادداشتهای طراحی Kafka idempotent producer را راهحل تکراریهای ناشی از resend میدانند، و بهروزرسانی با key را برای سمت consumer idempotent طبیعی و ذخیرهٔ offset کنار خروجی را برای سیستمهای بیرونی معرفی میکنند.
Idempotency-Keyدر Stripe رویPOSTطراحی مرجع شکل HTTP است: retry با همان کلید امن است؛ کلیدها حداکثر ۲۵۵ نویسهاند و ممکن است بعد از دستکم ۲۴ ساعت حذف شوند؛ و طبق مقالهٔ Leach کتابخانهٔ Ruby بهطور خودکار با کلید و backoff فزاینده و jitter retry میکند.- Amazon SQS FIFO، Azure Service Bus، NATS JetStream، Apache Pulsar هرکدام پنجرهٔ dedup سمت producer دارند (۵ دقیقه، بهطور پیشفرض ۱۰ دقیقه، بهطور پیشفرض ۲ دقیقه، بهطور پیشفرض خاموش)؛ هر چهار مستند میگویند id را برنامه انتخاب میکند، که همان نظمی است که کلید inbox میخواهد.
INSERT ... ON CONFLICT DO NOTHINGدر PostgreSQL primitive مستند تکstatement است که inbox در Go به آن تکیه دارد؛ PostgreSQL 19ON CONFLICT DO SELECTرا اضافه کرده، که مستند شده بهعنوان "idempotent insert or get or create".retry_after/--timeoutدر Laravel منبع مستند redelivery در workerهای لاراولاند؛UniqueLockوWithoutOverlappingدر کد فریمورکاند و قفل cache هستند، نه transaction.
در معماری: از یک پردازه تا سیستم توزیعشده (In architecture)
Monolith: یک پردازه، یک دیتابیس
اپ Laravel با صف database یا redis و یک PostgreSQL. یک listener وقتی OrderPaid اجرا میشود کیف پول را شارژ میکند. با idempotency طبیعی (UPDATE orders SET status = 'paid' WHERE status = 'pending') و projection با version check شروع کنید؛ job middleware به نام OncePerMessage را فقط برای handlerهایی اضافه کنید که اضافه میکنند، append میکنند یا بیرون صدا میزنند. چون جدولهای کسبوکاری و inbox یک دیتابیس دارند، یک DB::transaction دقیقش میکند. با afterCommit dispatch کنید تا job هرگز پیش از وجود ردیف اجرا نشود. معامله: چیزی برای هماهنگی نیست، پس سادهترین استفادهٔ درست برنده است.
Modular monolith و چند دیتابیس
ماژولها domain eventهای درونپردازهای منتشر میکنند (Domain Event و Integration Event) و handler هر ماژول یک consumer جداست. ستون consumer نام ماژول و handler است (billing.credit-wallet، notifications.send-receipt)، پس یک رویداد بهازای هر handler یک بار پردازش میشود. هر ماژول جدول inbox خودش را در schema خودش دارد؛ handler هرگز جدولهای ماژول دیگر را داخل transaction خودش نمینویسد. اگر ماژولی به دیتابیس خودش برود فقط connection string عوض میشود. دام: جدول inbox مشترک بدون ستون consumer باعث میشود handler اول «ببرد» و بقیه بیصدا رد شوند.
Microservices: outbox + inbox، با یک مثال
Orders رویداد OrderPlaced را منتشر میکند، Payments پول میگیرد، Shipping میفرستد. message id همان primary key ردیف outbox است (پایدار در retryهای relay)؛ هر سرویس مصرفکننده inbox خودش را در دیتابیس خودش دارد.
| قدم | سرویس | Transaction | پیام |
|---|---|---|---|
| 1 | Orders | ردیف سفارش + ردیف outbox (id=ord-7:placed) در یک commit | هنوز نه |
| 2 | relay سرویس Orders | حداقل یک بار publish میکند (بعد از crash ممکن است دو بار بفرستد) | OrderPlaced با id برابر ord-7:placed |
| 3 | Payments | inbox بهصورت (payments.charge, ord-7:placed) + ردیف پرداخت + ردیف outbox به نام pay-7:captured | PaymentCaptured |
| 3b | Payments (تحویل تکراری) | insert در inbox ۰ ردیف میزند؛ ack | هیچ |
| 4 | Shipping | inbox بهصورت (shipping.create-label, pay-7:captured) + ردیف برچسب | هیچ |
| 5 | Shipping به API حملونقل زنگ میزند | claim/perform/complete با Idempotency-Key: shipping.create-label:pay-7:captured | درخواست به carrier |
چه چیزی از مرز سرویسها عبور میکند: شناسهها، inbox در هر سرویس، و کلیدهای پاییندستی. چه چیزی نه: یک transaction واحد میان سرویسها، که برای همین یک saga جبران را هماهنگ میکند و جفت outbox + inbox تحویل effectively-once هر قدم را میدهد. قراردادهای سرویس و جریان پیام در ارتباط بین سرویسها و طراحی برای شکست: پیامرسانی قابلاتکا آمده است.
دادهی توزیعشده: replica، cache، shard، منطقه
- Replica: نوشتن inbox به primary میرود؛ هرگز تکراریبودن را روی read replica بررسی نکنید، lag «ندیدهام» را غلط میکند (Replication و Failover). بعد از failover ردیف inbox و ردیف کسبوکاری در یک transaction بودند، پس با هم گم یا حفظ میشوند: باز هم سازگار.
- Cache بهعنوان store dedup:
SET NXدر Redis سریع است ولی جدا از دیتابیس شماست: eviction، انقضا یا failover بیصدا markها را میاندازد (تکراری برمیگردد)، و mark بدون اثر (mark-then-process) کار را گم میکند. از آن فقط بهعنوان پیشفیلتر ارزان جلوی inbox دیتابیس استفاده کنید، هرگز بهجای آن برای اثرهای مهم. - دیتابیس shardشده: inbox را با همان key دادههای کسبوکاری shard کنید تا mark و اثر در یک shard و یک transaction باشند؛ اثر میانshard به two-phase commit یا saga نیاز دارد (Distributed SQL و Consensus). unique constraint سراسری در distributed SQL هماهنگی میانnode میخواهد و هزینه دارد.
- Active-active چندمنطقهای: unique constraint per-region است؛ دو منطقه میتوانند همان پیام را بپذیرند. هر key را به یک منطقهٔ مالک بفرستید، یا هر اثر را idempotent طبیعی کنید (CRDT برای شمارنده)، یا همگرایی نهایی با version check را بپذیرید.
- ساعتها: «جدیدتر» را با timestamp ساعت دیواری producerهای مختلف تشخیص ندهید؛ از version aggregate استفاده کنید (Eventual Consistency در دیتابیسها).
مسیر مقیاس: 1x، 10x، 100x
| بار | طراحی | تغییر |
|---|---|---|
| 1x (حدود ۱۰ پیام در ثانیه) | یک worker، یک ردیف inbox برای هر پیام، DELETE شبانه | چیز خاصی نیست؛ pg_total_relation_size را اندازه بگیرید |
| 10x (حدود ۱۰۰ پیام در ثانیه) | چند worker، insert دستهای inbox، پاکسازی با partition، lock_timeout | dedup دستهای، تنظیم autovacuum، مراقب اندازهٔ pool |
| 100x (۱۰۰۰+ پیام در ثانیه) | partition بر اساس زمان پیام، shard با key، پنجرهٔ کوتاهتر، مسیرهای داغ را به idempotency طبیعی یا offset-در-DB ببرید | جدول گلوگاه است: هر جا میشود حذفش کنید |
insert دستهٔ inbox (یک رفتوبرگشت برای هر batch، پیدا کردن اینکه کدام idها تازهاند):
-- returns only the ids that were NOT already in the inbox
INSERT INTO processed_messages (consumer, message_id)
SELECT 'wallet-credit', unnest($1::text[])
ON CONFLICT (consumer, message_id) DO NOTHING
RETURNING message_id;batch و اثرهایش هنوز باید یک transaction مشترک داشته باشند؛ اگر یکی از اثرها شکست بخورد کل batch (با markها) rollback میشود، پس اندازهٔ batch را به اندازهای بگیرید که حاضرید دوباره انجام دهید.
آزمایشگاه (Lab)
هر دستور و خروجی زیر expected, not run است مگر اینکه بنویسد «اجرا شد». بخشهای ارزانی که اجرا کردیم: تست Go (go test ./after/pginbox/ چاپ کرد ok)، بررسی syntax برای PHP، و statementهای ON CONFLICT روی SQLite 3 (شمارش 1, 0 برای inbox و 1, 0, 0, 1 برای projection با version check). هیچ broker یا PostgreSQL راهاندازی نشد.
Setup (PostgreSQL):
CREATE TABLE wallets (id text PRIMARY KEY, balance bigint NOT NULL);
INSERT INTO wallets VALUES ('w-7', 0);
CREATE TABLE processed_messages (
consumer text NOT NULL, message_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id));آزمایش ۱: تکراریها بدون inbox. همان واریز را سه بار تحویل بدهید (RabbitMQ: سه بار با همان message-id publish کنید؛ یا consumer را پیش از ack دوباره راه بیندازید):
$ psql -c "SELECT balance FROM wallets WHERE id='w-7'"
balance
---------
1500 -- expected: 3 x 500. Wrong: the message was one credit.آزمایش ۲: همان تحویلها با inbox.
$ go run ./after/rabbitmq # message-id: m-17, published three times
2026/11/25 10:00:01 m-17: processed
2026/11/25 10:00:01 m-17: duplicate
2026/11/25 10:00:01 m-17: duplicate
$ psql -c "SELECT balance FROM wallets WHERE id='w-7'"
balance
---------
500 -- expected
$ psql -c "SELECT count(*) FROM processed_messages"
count
-------
1آزمایش ۳: دو session روی یک id رقابت میکنند.
session A session B
BEGIN;
INSERT INTO processed_messages VALUES ('c','m-17'); BEGIN;
-- INSERT 0 1 INSERT INTO processed_messages VALUES ('c','m-17')
ON CONFLICT (consumer, message_id) DO NOTHING;
-- blocks (A uncommitted)
UPDATE wallets SET balance = balance + 500 ...;
COMMIT; -- unblocks: INSERT 0 0 (duplicate)آزمایش ۴: A rollback میکند، B ادامه میدهد. آزمایش ۳ را تکرار کنید ولی در A دستور ROLLBACK; بزنید: انتظار این است که insert در B برابر INSERT 0 1 شود و B handler را اجرا کند.
آزمایش ۵: crash میان اثر و ack. consumer را بعد از commit و پیش از ack با kill -9 بکشید (در handler یک time.Sleep بگذارید). انتظار: broker دوباره تحویل میدهد، log عبارت duplicate را نشان میدهد، و موجودی ۵۰۰ میماند.
آزمایش ۶: تکراری در هر broker (expected, not run).
# RabbitMQ: same message-id twice (check your rabbitmqadmin version's syntax)
rabbitmqadmin publish routing_key=wallet.credits payload='{"wallet_id":"w-7","amount":500}' properties='{"message_id":"m-17"}'
rabbitmqadmin publish routing_key=wallet.credits payload='{"wallet_id":"w-7","amount":500}' properties='{"message_id":"m-17"}'
# Kafka (kcat): same message-id header twice
echo '{"wallet_id":"w-7","amount":500}' | kcat -P -b localhost:9092 -t wallet.credits -H "message-id=m-17"
echo '{"wallet_id":"w-7","amount":500}' | kcat -P -b localhost:9092 -t wallet.credits -H "message-id=m-17"
# Redis Streams: two entries, two ids, same event_id; then a pending entry
redis-cli XGROUP CREATE wallet.credits wallet-credit 0 MKSTREAM
redis-cli XADD wallet.credits '*' event_id m-17 wallet_id w-7 amount 500
redis-cli XADD wallet.credits '*' event_id m-17 wallet_id w-7 amount 500
redis-cli XPENDING wallet.credits wallet-credit
redis-cli XAUTOCLAIM wallet.credits wallet-credit worker-2 60000 0-0
# Redis 8.6+: producer-side dedup; the second XADD returns the first entry id
redis-cli XADD wallet.credits IDMP billing-1 payment-42 '*' event_id payment-42 wallet_id w-7 amount 500
redis-cli XADD wallet.credits IDMP billing-1 payment-42 '*' event_id payment-42 wallet_id w-7 amount 500انتظار برای هر سه broker: balance روی ۵۰۰ میماند و processed_messages یک ردیف برای m-17 دارد (Redis: برای event_id).
آزمایش ۷: پنجرهٔ بیش از حد کوتاه. ردیف را زود پاک کنید و دوباره تحویل بدهید:
DELETE FROM processed_messages WHERE message_id = 'm-17'; -- simulate TTL expiry
-- redeliver m-17: expected, processed again, balance 1000بدفهمیهای رایج (Common misconceptions)
| باور | واقعیت |
|---|---|
| «broker ما exactly-once است، consumer نیازی به dedup ندارد» | تضمین broker تا خود broker است؛ نوشتن در دیتابیس یا فراخوانی HTTP در handler هنوز میتواند تکرار شود |
«SELECT و بعد INSERT بررسی امنی است» | دو worker هر دو «ندیدهام» میبینند؛ unique constraint خودِ بررسی است |
| «اول mark کنیم، ترتیب امن است» | crash بعد از mark اثر پیام را گم میکند؛ at-most-once در لباس مبدل |
| «key پیام در Kafka کلید dedup است» | entity را برای partitioning مشخص میکند؛ پیامهای بسیاری آن را دارند |
«topic-partition-offset همهٔ تکراریها را میگیرد» | redelivery یک record را میگیرد، نه producerی که رویداد را دو بار نوشته |
«redelivered = false یعنی میتوانم inbox را رد کنم» | ثابت میکند broker آن پیام را قبلاً تحویل نداده، نه اینکه producer آن را دو بار نفرستاده |
«ShouldBeUnique job را idempotent میکند» | dispatch را با قفل cache حذف میکند؛ handle() هنوز میتواند دو بار اجرا شود |
«WithoutOverlapping جلوی پردازش دوبار را میگیرد» | جلوی اجرای همزمان را میگیرد؛ redelivery بعد از پایان اولی بسته نمیشود |
«key در Redis با SET NX به خوبی ردیف inbox است» | سیستم دوم است: transaction مشترک ندارد، با eviction یا failover گم میشود |
| «dedup rowها را یک روز نگه دارید» | پنجره از مسیرهای retry، DLQ، replay و producer محاسبه میشود؛ حدس، تکراری را بیصدا برمیگرداند |
«inbox را بر اساس processed_at partition کنید و partitionهای قدیمی را drop کنید» | unique key باید partition key را داشته باشد، پس تکراریهای میانروزی رد میشوند؛ بر اساس ویژگی پیام partition کنید |
| «upsert idempotent همیشه idempotent است» | نه اگر delta بنویسد (qty = qty + EXCLUDED.qty) |
چکیده (Cheat sheet)
| موضوع | چه چیزی را یادتان بماند |
|---|---|
| الگو | BEGIN; INSERT mark ON CONFLICT DO NOTHING; if 0 rows skip; business write; COMMIT; ack |
| نگهبان | primary key به شکل (consumer, message_id)، نه SELECT |
| کلید | ساختهٔ producer، یک بار، پیش از اولین ارسال؛ business key برای تکراری معنایی |
| قاعدهٔ ack | بعد از commit، هم برای «processed» هم برای «duplicate» |
| ترتیب mark | فقط یک transaction درست است؛ دو commit یا تکراری میدهد یا گمشدن |
| اول طبیعی | set نه add؛ upsert با key؛ WHERE status = 'pending' شرطی؛ جدول set بهجای شمارنده |
| Projection | WHERE version < EXCLUDED.version؛ version از aggregate، نه ساعت |
| اثر بیرونی | Idempotency-Key پاییندستی بهعلاوهٔ lease؛ یا بر اساس پیامد at-least-once یا at-most-once را بپذیرید |
| TTL | پنجره = redelivery broker + retryها + مکث در DLQ + retry producer + حاشیه |
| پاکسازی | DELETE دستهای، یا partition بر اساس ویژگی پیام و drop |
| Kafka | idempotent producer و EOS برای Kafka-به-Kafkaاند؛ sinkهای دیتابیس inbox یا offset-در-DB میخواهند |
| RabbitMQ | message-id را ست کنید؛ redelivered وقتی ست است فقط hint است |
| Redis Streams | entry id برای redelivery؛ event_id یا IDMP (نسخهٔ 8.6 به بعد) برای retry producer |
| Laravel | ShouldBeUnique dispatch را dedup میکند؛ WithoutOverlapping سریال میکند؛ هیچکدام inbox نیست |
| تست | همان پیام را دو بار تحویل بدهید؛ بعد از mark شکست بدهید؛ یک اثر را ادعا کنید |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا brokerِ at-least-once بدون dedup سمت consumer هرگز کاملاً امن نیست؟ حیاتی
پاسخ
پاسخ: خرابی میان انجام اثر و acknowledge باعث میشود broker نداند اثر انجام شده یا نه، پس دوباره تحویل میدهد. retry producer و rebalance تکراری بیشتری میآورند. به تضمینهای تحویل نگاه کنید.
۲ — چرا SELECT پیش از INSERT dedup را امن نمیکند؟ حیاتی
پاسخ
پاسخ: دو worker همزمان هیچ ردیفی نمیبینند و هر دو جلو میروند. unique constraint که داخل transaction اجرا میشود primitive اصلی است؛ insert دوم منتظر نتیجهٔ transaction اول میماند و بعد conflict گزارش میکند.
۳ — «mark then process» در دو commit چه مشکلی دارد؟ حیاتی
پاسخ
پاسخ: crash بعد از mark و پیش از اثر، mark را سرجایش و اثر را غایب میگذارد؛ redelivery رد میشود و کار گم میشود (at-most-once).
۴ — چرا mark و اثر باید در یک transaction باشند، و چه چیزی آن را محدود میکند؟ حیاتی
پاسخ
پاسخ: تا با هم موفق یا ناموفق شوند. فقط وقتی کار میکند که اثر در همان دیتابیسِ جدول inbox باشد؛ اثرهای بیرونی کلید idempotency پاییندستی یا lease میخواهند.
۵ — سه منبع کلید idempotency و یک ضعف برای هرکدام را نام ببرید. مهم
پاسخ
پاسخ: message id ساختهٔ producer (باید پیش از اولین ارسال ساخته شود)؛ topic-partition-offset در Kafka (ارسال دوبارهٔ producer را نمیگیرد)؛ business key (تکرار قانونی برخورد میکند). همچنین entry id در Redis (XADD دوبارهارسالشده entry دوم میسازد).
۶ — TTL ردیفهای dedup را چطور انتخاب میکنید؟ مهم
پاسخ
پاسخ: بلندترین مسیرهای redelivery (redelivery broker، retry و backoff، مکث و replay در DLQ، افق retry producer) را جمع کنید و حاشیه بدهید. خیلی کوتاه بیصدا تکراری را برمیگرداند؛ خیلی بلند فضا هدر میدهد.
۷ — چرا partition کردن inbox بر اساس processed_at میتواند dedup را بشکند؟ تکمیلی
پاسخ
پاسخ: PostgreSQL میخواهد unique key روی جدول partitioned شامل partition key باشد، پس کلید processed_at را دارد؛ تکراریِ پردازششده در روز دیگر مقدار متفاوتی دارد و پذیرفته میشود. بر اساس ویژگیای partition کنید که روی هر نسخه یکسان است.
۸ — چرا transactionهای exactly-once کافکا inbox نیستند؟ مهم
پاسخ
پاسخ: recordهای خروجی و offsetهای consumer را داخل Kafka بهصورت atomic commit میکنند. نوشتن در دیتابیس در handler بیرون از آن transaction است، پس redelivery هنوز میتواند آن را تکرار کند؛ inbox یا offset کنار خروجی لازم است.
۹ — تفاوت ShouldBeUnique و consumer idempotent چیست؟ حیاتی
پاسخ
پاسخ: ShouldBeUnique قفل cache میگیرد تا تا وقتی job معادل در صف یا در حال اجراست dispatch دوم نشود. جلوی اجرای دوبارهٔ handle() یک job در redelivery را نمیگیرد و قفل در transaction شما نیست.
۱۰ — version check چطور projection را idempotent و تحملکنندهٔ بیترتیبی میکند؟ مهم
پاسخ
پاسخ: upsert رویداد را فقط وقتی اعمال میکند که versionاش از version ذخیرهشده بیشتر باشد، پس replay (مساوی) و رویداد کهنه (کمتر) صفر ردیف را عوض میکنند و رویداد جدیدتر اعمال میشود.
۱۱ — webhook شخص ثالث ممکن است در سه روز پنج بار برسد. چه کلید و پنجرهای؟ حیاتی
پاسخ
پاسخ: id رویداد ارائهدهنده بهعنوان کلید، با دامنهٔ consumer، و پنجرهای بلندتر از برنامهٔ retry آنها (سه روز بهعلاوهٔ حاشیه).
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
| Idempotent | تکرار عملیات همان وضعیت انجام یکباره را میدهد |
| Idempotent consumer / receiver | consumer (در EIP: Idempotent Receiver) که میتواند چند بار همان پیام را با خیال راحت دریافت کند |
| Duplicate delivery (تحویل تکراری) | همان پیام بیش از یک بار به consumer داده شده |
| At-least-once | semantics تحویلی که پیام را گم نمیکند ولی ممکن است تکرارش کند |
| Effectively-once | تحویل at-least-once بهاضافهٔ اثر idempotent: یک اثر قابلمشاهده |
| Idempotency key (کلید idempotency) | هویت پایدار یک پیام منطقی برای تشخیص تکرار |
| Message id | شناسهٔ یکتای انتخابی producer برای یک پیام منطقی (message-id در RabbitMQ) |
| Business key | شناسهٔ دامنهای معنا (payment_id) که میتواند کلید dedup باشد |
| Coordinates | topic-partition-offset در Kafka، که broker هنگام append میسازد |
| Entry id | شناسهٔ ms-seq در Redis Streams که XADD میسازد |
IDMP / IDMPAUTO | حالتهای XADD در Redis 8.6 برای dedup سمت producer با producer id + idempotent id، یا با hash محتوا |
| Inbox (dedup) table | processed_messages: یک ردیف برای هر پیام انجامشده، primary key برابر (consumer, message_id) |
| Full inbox | جدولی که کل پیامهای ورودی را بافر میکند و async پردازش میشود |
| Consumer name | دامنهٔ کلید dedup؛ هر پیام برای هر consumer یک بار پردازش میشود |
ON CONFLICT DO NOTHING | بند PostgreSQL/SQLite که insert نقضکنندهٔ unique constraint را رد میکند و صفر ردیف گزارش میدهد |
INSERT IGNORE | شکل MySQL که ردیفهایی را که خطایی مثل duplicate میدهند رد میکند |
unique_violation (23505) | SQLSTATE پستگرس برای شکست unique constraint |
ER_DUP_ENTRY (1062) | خطای duplicate-key در MySQL |
| Mark | نوشتن شناسهٔ پیام در inbox |
| Process then mark | اول اثر، بعد ثبت؛ شکاف crash اثر را تکرار میکند |
| Mark then process | اول ثبت، بعد اثر؛ شکاف crash اثر را گم میکند |
| Dedup window (پنجرهٔ dedup) | بلندترین فاصله میان اولین و آخرین نسخهٔ ممکن یک پیام |
| TTL (ردیف dedup) | مدت نگهداشتن ردیف؛ از پنجرهٔ dedup به دست میآید |
| Lease | claim زماندار (lease_until) که اجازه میدهد claimکنندهٔ crashکرده جایگزین شود |
| Claim، perform، complete | ماشین حالت برای اثرهای غیرتراکنشی |
| Downstream idempotency key | کلیدی که به سیستم بیرونی داده میشود تا فراخوانیهای تکراری را dedup کند |
| Natural idempotency (idempotency طبیعی) | عملیاتی که هر چندبار اجرا شود به همان وضعیت همگرا میشود (set، upsert، update شرطی) |
| Version check | رویداد را فقط وقتی اعمال کن که versionاش از version ذخیرهشده جدیدتر باشد |
| Projection / read model | جدولی که از رویدادها برای query ساخته میشود |
ShouldBeUnique | interface لاراول که uniqueId یک job را در cache قفل میکند تا dispatch تکراری نشود |
WithoutOverlapping | job middleware لاراول که jobها را با key و قفل cache سریال میکند |
uniqueFor / #[UniqueFor] | ثانیههایی که پس از آن قفل unique در لاراول آزاد میشود (پیشفرض ۰ یعنی هرگز منقضی نمیشود) |
retry_after | تنظیم صف لاراول که پس از آن job رزروشده دوباره امتحان میشود |
redelivered flag | flag در RabbitMQ که وقتی پیام قبلاً تحویل و requeue شده ست میشود؛ فقط hint |
| PEL | لیست pending entries در Redis Streams: تحویلشده، هنوز acknowledge نشده |
XAUTOCLAIM | فرمان Redis که entryهای idle در PEL را برمیدارد |
| Exactly-once semantics (EOS) | consume-transform-produce تراکنشی Kafka داخل Kafka |
| Idempotent producer | قابلیت producer در Kafka که retryهای خودش را با شمارهٔ sequence dedup میکند |
| Outbox + inbox | publish تضمینشدهٔ سمت producer بههمراه dedup سمت consumer |
| Partition key (جدول) | ستون(های) هدایتکنندهٔ ردیف به partition جدول؛ باید در unique keyها باشد |
lock_timeout | تنظیم PostgreSQL که statementی را که زیادی منتظر lock مانده abort میکند (55P03) |
منابع (References)
- Chris Richardson، "Pattern: Idempotent Consumer"، microservices.io. microservices.io
- Hohpe و Woolf، "Idempotent Receiver"، Enterprise Integration Patterns. enterpriseintegrationpatterns.com
- Brandur Leach، "Designing robust and predictable APIs with idempotency"، Stripe، ۲۲ فوریهٔ ۲۰۱۷. stripe.com
- مستندات API استریپ، Idempotent requests. docs.stripe.com
- J. Jena، S. Dalal، D. Tishkin، "The Idempotency-Key HTTP Header Field"، Internet-Draft draft-ietf-httpapi-idempotency-key-header (work in progress). datatracker.ietf.org
- مستندات PostgreSQL: INSERT، Index Uniqueness Checks، Table Partitioning، Transaction Isolation، Error Codes
- SQLite، UPSERT. sqlite.org
- MongoDB manual، Unique Indexes. mongodb.com
- مستندات Redis: Streams، Idempotent message processing، XADD، SET
- مستندات Apache Kafka: Design, message delivery semantics، KafkaProducer Javadoc؛ KIPها: KIP-98، KIP-447
- مستندات RabbitMQ: Publishers، Reliability، Consumer Acknowledgements and Publisher Confirms
- NATS، JetStream model deep dive؛ Apache Pulsar، Message deduplication؛ Amazon SQS، Using the message deduplication ID؛ Azure Service Bus، Duplicate detection
- مستندات Laravel 13: Queues (unique jobs،
WithoutOverlapping، database transactions)، Query builder؛ کد فریمورک: UniqueLock، WithoutOverlapping - پکیجها: mateusjunges/laravel-kafka، message handlers، vladimir-yuldashev/laravel-queue-rabbitmq
- Go: amqp091-go، franz-go kgo، go-redis، pgx
- ثابتهای خطای MySQL (فهرست شخص ثالث): VividCortex/mysqlerr
- همچنین ببینید: تضمینهای تحویل، تأیید پیام، ترتیب و Partitioning، Transactional Outbox، Dead-Letter Queue، Retry، Backoff و Delayed Delivery، Saga Pattern، تست سیستمهای پیامرسانی