Event Sourcing & CQRS
“Capture all changes to an application state as a sequence of events.” — Martin Fowler, Event Sourcing
خلاصه: منبعیابی رویداد (Event Sourcing) بهجای وضعیت فعلی، خودِ واقعیتهایی را که سیستم را تغییر دادهاند ذخیره میکند و وضعیت را از آنها میسازد؛ CQRS مدلی را که داده را تغییر میدهد از مدلی که به پرسشها پاسخ میدهد جدا میکند. تمرکز: یک event store درست (stream، expected version، global position به ترتیب commit، command receipt)، replay و snapshot، projection با checkpoint و rebuild امن، نسخهبندی رویداد، و آنچه brokerها میتوانند و نمیتوانند انجام دهند. هدف یادگیری: بتوانید مدل نوشتنِ مبتنی بر رویداد و read modelهای آن را بسازید و اجرا کنید، بیآنکه رویدادی گم، تکرار یا جابهجا شود؛ و بدانید چه وقت هیچکدام از این دو الگو ارزش هزینهاش را ندارد.
این فصل مالک event store و هر چیزی است که از آن مشتق میشود. تفاوت event notification، event-carried state transfer و event sourcing بهعنوان سبکهای یکپارچهسازی در معماری رویدادمحور آمده است؛ انتشار مطمئن از جدولهای معمولی در الگوی outbox؛ دریافت تغییرات از لاگ پایگاه داده در CDC؛ و پنجرهها و watermarkها در پردازش جریان. در این صفحه پایگاه داده منبع حقیقت (System of record) است و brokerها فقط وسیلهٔ انتقالاند.
نقشهٔ صفحه
| دنبال چه هستید؟ | بخش مربوط |
|---|---|
| یک event store دقیقاً چه تضمینی باید بدهد | Event store و stream |
| چرا دو نویسنده نمیتوانند هر دو نسخهٔ ۸ را بنویسند | Expected version |
چرا cursor مبتنی بر bigserial رویداد گم میکند | Global position |
| بارگذاری سریعتر streamهای طولانی | Replay و snapshot |
| read model، checkpoint و انحراف از حقیقت | Projection |
| بازسازی read model بدون توقف سرویس | Rebuild |
| تغییر شکل رویدادی که قبلاً ذخیره شده | نسخهبندی و upcasting |
| CQRS روی یک پایگاه داده و بدون رویداد | CQRS |
| «ذخیره کردم، چرا فهرست هنوز قدیمی است؟» | Read-your-writes |
| تکرار فرمانی که COMMIT آن timeout شد | Command receipt |
| اصلاح یک رویداد اشتباه | اصلاحها |
| حذف دادهٔ شخصی از لاگ تغییرناپذیر | حریم خصوصی و حذف |
| compaction در Kafka بهعنوان event store | Log compaction |
| جزئیات RabbitMQ، Kafka و Redis Streams | تفاوت brokerها |
| چه وقت هیچکدام را انجام ندهیم | انتخاب |
همهچیز در یک دقیقه
| اصطلاح | به زبان ساده | مثال کوچک | پیامد بدفهمی |
|---|---|---|---|
| رویداد (Event) | واقعیتی در زمان گذشته | MoneyWithdrawn{amount: 30} | ذخیرهٔ command بهجای event یعنی replay نیتها، نه نتیجهها |
| Stream | همهٔ رویدادهای یک aggregate | acc-42 نسخههای 1..17 | قواعد بین چند stream بیصدا بررسی نمیشوند |
| Expected version | «فقط اگر stream هنوز در نسخهٔ v است اضافه کن» | انتظار 17، store در 18: رد | دو برداشت هر دو از بررسی موجودی عبور میکنند |
| Global position | ترتیب همهٔ رویدادها به ترتیب commit | 811، 812، 813 بدون شکاف | projector رویدادی را که دیر commit شد جا میاندازد |
| Replay | fold همهٔ رویدادها از ابتدا برای ساخت وضعیت | 17 رویداد ← موجودی 70 | replay دوباره ایمیل میفرستد |
| Snapshot | نتیجهٔ fold تا یک نسخه، ذخیرهشده | وضعیت در v1000 + دنباله | snapshot از وضعیت ذخیرهنشده «حقیقت» میشود |
| Projection | کدی که رویداد را به read model تبدیل میکند | ردیفهای account_balances | checkpoint از روی رویداد ناموفق جلو میرود |
| Upcaster | تبدیل شکل قدیمی رویداد هنگام خواندن | v1 amount_cents ← v2 amount | رویداد قدیمی کد جدید را میشکند یا غلط خوانده میشود |
| Command receipt | پاسخ ذخیرهشده برای یک command ID | تکرار دوباره نسخهٔ 18 را برمیگرداند | timeout و تکرار، دو بار برداشت میکند |
| Compensating event | واقعیت جدیدی که اثر قبلی را برمیگرداند | WithdrawalReversed | ویرایش تاریخچه ردّ ممیزی را نابود میکند |
| الگو | نیاز دارد به | نیاز ندارد به | هزینهٔ معمول |
|---|---|---|---|
| CQRS | مدلهای جدا برای command و query | رویداد، broker، پایگاه دادهٔ جدا، eventual consistency | نگهداشتن سازگاری دو مدل |
| Event sourcing | رویداد بهعنوان منبع حقیقت و fold قابل replay | CQRS، broker، میکروسرویس | نسخهبندی، projection، طراحی حذف داده |
| هر دو با هم | projectionها مدل query را از event store میسازند | Kafka | read model ناهمگام و عملیات rebuild |
از کجا آمده
مقالهٔ مارتین فاولر (Fowler) در سال ۲۰۰۵ این الگو را نامگذاری کرد و فایدههایش را برشمرد: بازسازی کامل وضعیت با اجرای دوبارهٔ لاگ، پرسوجوی زمانی (Temporal query) مثل «وضعیت در ۵ دسامبر چه بود؟» و replay برای اصلاح گذشته. همان مقاله دربارهٔ سیستمهای بیرونی هشدار میدهد: replay نباید پیامها را دوباره بفرستد، پس gatewayها باید بدانند در حالت replay هستند؛ و پاسخ پرسوجوهای بیرونی (مثلاً نرخ ارز در یک تاریخ) باید برای replay وفادار به گذشته نگه داشته شود.
مستند CQRS Documents از گرگ یانگ (Greg Young)، که در ۲۰۱۰ و بهعنوان جزوهٔ کلاس منتشر شد، CQRS را تقسیم یک شیء به سمت command و سمت query توصیف میکند که بر اصل Command–Query Separation برتراند مِیر بنا شده است؛ و آن را با event sourcing جفت میکند: لاگ رویداد append-only، کنترل همروندی خوشبینانه (Optimistic concurrency) روی نسخهٔ موردانتظار stream، snapshotهای غلتان (Rolling snapshot) بهعنوان میانبُری برای بارگذاری، و تراکنش معکوس (Reversal transaction) بهجای حذف. یادداشت CQRS فاولر در ۲۰۱۱ هشدار میدهد که بیشتر سیستمها با مدل CRUD جور هستند و CQRS را باید در bounded contextهای مشخص به کار برد، نه در کل سیستم؛ همچنین میگوید دو مدل میتوانند یک پایگاه داده را مشترک داشته باشند.
محصولات بعدی: EventStoreDB که اکنون KurrentDB نام دارد، پایگاه دادهای است که حول stream ساخته شده و هنگام append نسخهٔ موردانتظار را بررسی میکند؛ Marten پایگاه PostgreSQL را برای .NET به document store و event store تبدیل میکند؛ Axon Framework روی JVM، aggregate، پردازشگر رویداد و snapshot فراهم میکند؛ و spatie/laravel-event-sourcing مفهوم aggregate، projector و reactor را به Laravel میآورد. برای بهکاربردن این الگوها هیچکدام لازم نیست؛ این فصل store را مستقیم روی PostgreSQL میسازد.
چرا وجود دارد
جدول وضعیت فعلی به «موجودی چقدر است؟» ارزان و درست پاسخ میدهد؛ اما به «چرا؟»، «به چه ترتیبی؟» یا «سهشنبهٔ گذشته چه فکر میکردیم؟» پاسخی ندارد، مگر اینکه یک ردّ ممیزی جداگانه بنویسیم و آن را با جدول هماهنگ نگه داریم.
| ذخیرهٔ وضعیت فعلی (CRUD) | Event sourcing |
|---|---|
| یک ردیف برای هر موجودیت که درجا بهروز میشود | یک ردیف تغییرناپذیر برای هر واقعیت که اضافه میشود |
| پرسوجوی ساده و ابزارهای پخته | پرسوجو به projection یا fold نیاز دارد |
| تاریخچه اختیاری است و میتواند با وضعیت ناسازگار شود | تاریخچه همان وضعیت است؛ وضعیت فعلی مشتق میشود |
| یک باگ ردیف را خراب میکند و مقدار قبلی از دست میرود | یک باگ projection را خراب میکند و آن را از لاگ بازمیسازیم |
| migration اسکیما ردیفها را بازنویسی میکند | رویدادهای قدیمی میمانند و خوانندهها upcast میکنند |
حذف داده یعنی یک DELETE | حذف به طراحی نیاز دارد (crypto-shredding، retention) |
تصویر روزمرهای که در ادامه دوباره به کار میرود: دفتر حساب یک مغازهٔ کوچک. حسابدار هرگز سطری را پاک نمیکند؛ برای اشتباه، سطر اصلاحی تازهای مینویسد. «مانده»ای که پایین هر صفحه نوشته میشود فقط برای راحتی است (snapshot)، و گزارش هفتگیِ روی دیوار یک projection است که هر وقت بخواهیم از روی دفتر از نو نوشته میشود. اگر دو حسابدار در یک دفتر بنویسند، قاعدهای لازم است: سطر ۱۸ را فقط وقتی بنویس که آخرین سطر هنوز ۱۷ باشد.
سه بدفهمی را همین ابتدا کنار بگذاریم:
- CQRS به معنای event sourcing، broker یا eventual consistency نیست. مدل query میتواند یک view در SQL یا جدولی باشد که در همان تراکنش بهروز میشود.
- Event sourcing یعنی «رویداد را در Kafka منتشر کن» نیست. store باید expected version را بررسی کند و ترتیبی بدون شکاف بدهد؛ topic در broker هیچکدام را برایتان انجام نمیدهد.
- تغییرناپذیر به معنای حذفنشدنی نیست. retention، نابودی کلید و حذف stream وجود دارند؛ باید طراحی شوند و بهتنهایی سیستم را با هیچ قانونی سازگار نمیکنند.
واقعاً دربارهٔ چیست
سه تابع و دو تضمین. تابع decide(state, command) → events قواعد ثابت (Invariant) را بررسی میکند؛ evolve(state, event) → state واقعیتها را بهشکل قطعی fold میکند؛ project(event) → read model change مدلهای query را میسازد. store تضمین میکند که append به stream فقط در نسخهٔ موردانتظار موفق شود، و هر رویداد commitشده global positionی بگیرد که خوانندهها بتوانند بدون جاانداختن حتی یک مورد دنبالش کنند.
مسیر نوشتن یک تراکنش پایگاه داده است: قفلکردن تخصیصدهندهٔ موقعیت (Feed allocator)، بررسی command receipt، fold کردن stream، تصمیم، compare-and-set روی سر stream، درج رویدادها، جلو بردن allocator، ذخیرهٔ receipt و commit. مسیر خواندن ناهمگام است: projector رویدادهای بعد از checkpoint خود را میخواند و ردیفها و checkpoint را در یک تراکنش بهروز میکند. relayها همین feed را برای سرویسهای دیگر به brokerها کپی میکنند.
فهرست مفاهیم
Event store و stream حیاتی
به زبان ساده: event store جدولی فقطافزودنی (Append-only) از واقعیتهاست که در streamها گروهبندی شدهاند؛ هر stream تاریخچهٔ یک چیز است.
بدفهمی رایج: «هر لاگی event store است.» لاگی که نتواند append متعارض را رد کند یا نتوان آن را برای هر stream به ترتیب خواند، وسیلهٔ انتقال است، نه منبع حقیقت.
تعریف: stream دنبالهٔ مرتب رویدادهای یک aggregate (یک حساب، یک سفارش) است که بدون شکاف ۱، ۲، ۳ شماره میخورد. event store این امکانات را میدهد: append اتمیک یک یا چند رویداد به یک stream در نسخهٔ موردانتظار، خواندن مرتب یک stream، و خواندن مرتب همهٔ streamها (feed سراسری). event store append-only است: رویدادها هرگز بهروز نمیشوند؛ اسکیمای PostgreSQL زیر این را با trigger اجبار میکند.
1 Client -> Execute: withdraw 30 from acc-42, command_id c-77
2 Execute -> events: SELECT ... WHERE stream_id = 'acc-42' ORDER BY stream_version
3 Execute -> fold: v1 AccountOpened, v2 MoneyDeposited 100 -> balance 100
4 Execute -> decide: 30 <= 100 -> MoneyWithdrawn{30}
5 Execute -> events: INSERT stream_version 3, global_position 812سناریوهای واقعی: کیف پولی که برای رسیدگی به اعتراض به ترتیب دقیق برداشتها نیاز دارد؛ سفارشی که ماشین حالتش باید قابل ممیزی باشد؛ سیستم رزروی که باید بگوید «ساعت ۱۰:۰۲ صندلی 14C دست چه کسی بود»؛ تیم انطباق که میپرسد سیستم در یک زمان مشخص چه میدانست.
| محصول | مفهوم stream | بررسی هنگام append | ترتیب سراسری |
|---|---|---|---|
| PostgreSQL (این فصل) | stream_id + stream_version | CAS روی streams.version و UNIQUE (stream_id, stream_version) | global_position که زیر قفل ردیف تخصیص مییابد |
| KurrentDB (EventStoreDB) | stream نامدار با revision | streamState: any، no_stream، stream_exists یا revision دقیق | stream ویژهٔ $all |
| Marten (PostgreSQL، .NET) | شناسهٔ stream + نسخه | بررسی خوشبینانهٔ نسخه هنگام append | sequence رویداد بههمراه high water mark |
| Axon Framework | stream رویداد aggregate | توسط framework مدیریت میشود؛ در صفحههای خواندهشده نیامده | tracking token برای پردازشگرهای streaming |
| Kafka | key درون یک partition | ندارد | فقط درون هر partition |
| Redis Streams | یک key برای هر stream | IDهای صریح باید صعودی باشند؛ بررسی نسخه ندارد | فقط درون هر key |
روش استفاده: برای هر مرز سازگاری (Consistency boundary) یک stream نگه دارید، تا جای ممکن streamها را کوتاه کنید (مثلاً یک stream برای هر حساب در هر سال طرحی معتبر است) و قواعد بین چند stream را به saga یا یک stream اختصاصی بسپارید. اسکیما:
-- PostgreSQL event store, read model and checkpoints for the Go and Laravel snippets.
-- Run once in an empty schema. Amounts are integer minor units of one currency per account.
CREATE TABLE feed_allocator (
id smallint PRIMARY KEY CHECK (id = 1),
next_position bigint NOT NULL CHECK (next_position >= 1)
);
INSERT INTO feed_allocator (id, next_position) VALUES (1, 1);
CREATE TABLE streams (
id text PRIMARY KEY,
version bigint NOT NULL CHECK (version >= 1)
);
CREATE TABLE events (
global_position bigint PRIMARY KEY, -- assigned under the allocator row lock
event_id text NOT NULL UNIQUE,
stream_id text NOT NULL REFERENCES streams (id),
stream_version bigint NOT NULL CHECK (stream_version >= 1),
type text NOT NULL,
schema_version int NOT NULL CHECK (schema_version >= 1),
data jsonb NOT NULL,
command_id text NOT NULL,
occurred_at timestamptz NOT NULL, -- event time: when it happened in the business
recorded_at timestamptz NOT NULL DEFAULT now(), -- processing time: when the store accepted it
UNIQUE (stream_id, stream_version) -- backstop for the expected-version check
);
-- Append-only at the database level, not just by convention.
CREATE FUNCTION events_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'events is append-only' USING ERRCODE = 'insufficient_privilege';
END $$;
CREATE TRIGGER events_no_update BEFORE UPDATE OR DELETE ON events
FOR EACH ROW EXECUTE FUNCTION events_append_only();
CREATE TRIGGER events_no_truncate BEFORE TRUNCATE ON events
FOR EACH STATEMENT EXECUTE FUNCTION events_append_only();
-- One row per accepted command: answers retries whose first COMMIT outcome was unknown.
CREATE TABLE command_receipts (
command_id text PRIMARY KEY,
stream_id text NOT NULL,
fingerprint text NOT NULL, -- SHA-256 of the command intent
stream_version bigint NOT NULL,
last_position bigint NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE snapshots (
stream_id text PRIMARY KEY REFERENCES streams (id),
version bigint NOT NULL,
format int NOT NULL, -- bump when the state shape or fold logic changes
state jsonb NOT NULL,
taken_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE projection_checkpoints (
projection text PRIMARY KEY, -- e.g. balances_v1, balances_v2, relay:kafka
position bigint NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Several projection versions live side by side; readers follow active_projections.
CREATE TABLE account_balances (
projection text NOT NULL REFERENCES projection_checkpoints (projection),
account_id text NOT NULL,
currency char(3) NOT NULL,
balance bigint NOT NULL CHECK (balance >= 0),
stream_version bigint NOT NULL,
last_occurred_at timestamptz NOT NULL,
PRIMARY KEY (projection, account_id)
);
CREATE TABLE active_projections (
read_model text PRIMARY KEY, -- e.g. balances
projection text NOT NULL REFERENCES projection_checkpoints (projection)
);
-- Crypto-shredding: deleting a subject's key makes its sealed fields unreadable.
CREATE TABLE subject_keys (
subject_id text PRIMARY KEY,
data_key bytea NOT NULL CHECK (length(data_key) = 32),
created_at timestamptz NOT NULL DEFAULT now()
);نسخهٔ موردانتظار و همروندی خوشبینانه (Expected version / Optimistic concurrency) حیاتی
به زبان ساده: «من نسخهٔ ۱۷ را خواندم؛ رویدادم را بهعنوان ۱۸ ذخیره کن، فقط اگر کس دیگری زودتر این کار را نکرده باشد.»
بدفهمی رایج: «قید UNIQUE کافی است.» این قید جلوی دو ردیف با نسخهٔ ۱۸ را میگیرد؛ اما نویسندهای که بر اساس وضعیت کهنه تصمیم گرفته و پس از ۱۸ِ دیگری نسخهٔ ۱۹ را حساب کرده، از آن عبور میکند. بررسی باید نسخهای را مقایسه کند که تصمیم بر آن بنا شده است.
تعریف: کنترل همروندی خوشبینانه روی stream یعنی append یک نسخهٔ موردانتظار همراه دارد و اگر سر stream متفاوت باشد شکست میخورد. مقدارهای ویژه از حالتهای stream در KurrentDB الهام گرفتهاند: AnyVersion (بدون بررسی)، NoStream (نباید وجود داشته باشد)، یا یک عدد دقیق.
Writer A (balance 100) Writer B (balance 100)
1 load acc-42 -> v2, balance 100
2 load acc-42 -> v2, balance 100
3 decide withdraw 80 -> expected v2
4 UPDATE streams SET version = 3 WHERE version = 2 -- 1 row
5 COMMIT
6 decide withdraw 80 -> expected v2
7 UPDATE ... WHERE version = 2 -- 0 rows
8 ErrWrongExpectedVersion: reload, decide again -> insufficient fundsسناریوهای واقعی: دو خودپرداز که همزمان از یک حساب برداشت میکنند؛ دو کارشناس پشتیبانی که یک سفارش را ویرایش میکنند؛ کلاینت موبایلی که ویرایشی را از صفحهای ده دقیقه پیشبارگذاریشده میفرستد (expected version از سمت کلاینت، یعنی UI خوشبینانه)؛ دو نمونه از یک consumer که هر دو به یک رویداد واکنش نشان میدهند.
| محصول | نشانهٔ شکست |
|---|---|
| CAS در PostgreSQL (این فصل) | UPDATE صفر ردیف تغییر میدهد؛ قید UNIQUE بهعنوان پشتیبان خطای SQLSTATE 23505 میدهد |
| کلاینتهای KurrentDB | append وقتی stream در حالت موردانتظار نیست شکست میخورد (نوع خطا در هر کلاینت فرق دارد) |
| NATS JetStream | اگر Nats-Expected-Last-Subject-Sequence مطابقت نداشته باشد publish رد میشود |
| Kafka، Redis Streams، RabbitMQ | بررسی نسخه برای هر key ندارند؛ برنامه باید جای دیگری فراهمش کند |
روش استفاده: با ErrWrongExpectedVersion دوباره بارگذاری کنید، دوباره تصمیم بگیرید و با expected version جدید اما همان command ID تکرار کنید. در store زبان Go قفل سراسری allocator از قبل appendها را پشت سر هم میکند؛ پس CAS لایهٔ دفاعی است که اگر نویسندهای Execute را دور بزند همچنان برقرار میماند.
موقعیت سراسری و ترتیب commit (Global position) حیاتی
به زبان ساده: projectorها «همهچیز بعد از موقعیت N» را میخوانند. این فقط وقتی کار میکند که پس از عبور شما، رویدادی با شمارهٔ کوچکتر دیگر ظاهر نشود.
بدفهمی رایج: «bigserial ترتیب را میدهد.» مقدار sequence هنگام درج ردیف گرفته میشود، نه هنگام commit. مستند PostgreSQL صریحاً میگوید مقدارها با abort تراکنش پس گرفته نمیشوند و sequence برای شمارهگذاری بدون شکاف مناسب نیست. بدتر اینکه مقدار کوچکتر ممکن است بعد از مقدار بزرگتر قابل دیدن شود.
تعریف: global position ترتیبی کامل روی رویدادهای commitشده با دو ویژگی است: بدون شکاف، و ترتیب commit: اگر خوانندهای موقعیت p را ببیند، همهٔ موقعیتهای کمتر از p را هم میبیند. این store هر دو را با نگهداشتن قفل FOR UPDATE روی تنها ردیف جدول feed_allocator تا لحظهٔ COMMIT به دست میآورد؛ مستند PostgreSQL میگوید قفل ردیف تا پایان تراکنش میماند و در Read Committed، SELECT FOR UPDATEِ منتظر پس از commit تراکنش اول، نسخهٔ بهروزشدهٔ ردیف را برمیگرداند.
T1 (bigserial) T2 (bigserial) Projector
1 INSERT -> position 41 (open)
2 INSERT -> position 42
3 COMMIT
4 SELECT > 40 -> [42]; checkpoint = 42
5 COMMIT
6 SELECT > 42 -> [] -- 41 never projectedسناریوهای واقعی: read model موجودی که یک واریز را برای همیشه ندارد؛ relay یکپارچهسازی که یک سفارش را هیچوقت منتشر نمیکند؛ تراکنشی طولانی (یک trigger کند، یک انتظار قفل) که این پنجره را از میکروثانیه به دقیقه میرساند. «پنجرهٔ ایمنی» چندثانیهای راهحل نیست، چون تراکنش میتواند بهطور دلخواه باز بماند.
| رویکرد | چطور ترتیب را تضمین میکند | هزینه |
|---|---|---|
| قفل ردیف allocator (این فصل) | appender بعدی تا قابلدیدنشدن commit قبلی منتظر میماند | همهٔ appendها سریالیاند و توان عملیاتی به یک تراکنش در هر لحظه محدود است |
| تشخیص شکاف (async daemon در Marten) | high water mark فقط تا زیر اولین حفره جلو میرود و حفره وقتی رد میشود که هیچ تراکنشی نتواند پرش کند | پیچیده؛ پشت تراکنشهای طولانی متوقف میشود |
| CDC مبتنی بر لاگ (logical decoding در PostgreSQL) | تغییرات به ترتیب commit صادر میشوند | عملیات replication slot؛ ببینید CDC |
پایگاه داده با ترتیب $all داخلی (KurrentDB) | خود store تخصیص میدهد | یک پایگاه دادهٔ جدا برای نگهداری |
روش استفاده: اندازه بگیرید. یک تراکنش برای هر append که قفل را چند میلیثانیه نگه دارد، صدها append در ثانیه برای هر پایگاه داده میدهد؛ چند رویداد را در یک command دسته کنید و تراکنش را کوتاه نگه دارید (هیچ فراخوانی شبکه درون آن نباشد). بالاتر از این، بهجای سستکردن تضمین، سراغ تشخیص شکاف یا CDC بروید.
بازپخش و snapshot (Replay / Snapshot) مهم
به زبان ساده: replay وضعیت را با fold همهٔ رویدادها از نو میسازد؛ snapshot وضعیت foldشده در نسخهٔ v را نگه میدارد تا بارگذاری بعدی فقط دنباله را fold کند.
بدفهمی رایج: «از aggregateی که بعد از اجرای command در حافظه دارم snapshot بگیر.» آن شیء ممکن است رویدادهای تصمیمگرفته اما commitنشده داشته باشد. snapshot فقط باید از تاریخچهٔ commitشده گرفته شود.
تعریف: گرگ یانگ اینها را rolling snapshot مینامد: خلاصهای غیرنرمال از وضعیت aggregate در نقطهای از stream که بهعنوان میانبُر، از بارگذاری کل تاریخچه جلوگیری میکند. snapshot یک بهینهسازی است و هرگز منبع حقیقت نیست: همهٔ snapshotها را پاک کنید و سیستم باید همچنان درست کار کند.
1 SaveSnapshot(acc-42) -> REPEATABLE READ: head v1000, fold v1..v1000
2 SaveSnapshot -> UPSERT snapshots(v1000, format 1) only if stored version/format is older
3 Load(acc-42) -> snapshot v1000 valid (id, version <= head, format) -> fold v1001..v1004
4 Deploy changes fold rules -> SnapshotFormat = 2 -> old snapshots ignored, full replayسناریوهای واقعی: کالای انبار با سالها جابهجایی موجودی؛ یک اشتراک طولانیمدت؛ aggregateی که زمان بارگذاریاش بخش اصلی تأخیر command است. مستند Axon همین انگیزه را میآورد (رویدادهای فراوان برای aggregate عمرطولانی) و snapshot را با آستانهها راه میاندازد؛ snapshot در Spatie ویژگیهای public aggregate را ذخیره میکند.
| قاعده | دلیل |
|---|---|
| snapshot از رویدادهای commitشده و درون یک تراکنش REPEATABLE READ | سر stream، snapshot و دنباله یک دید سازگار میسازند |
| هنگام بارگذاری، stream ID، نسخهٔ کمتر یا مساوی head و نسخهٔ قالب را بررسی کنید | snapshot کپیشده یا کهنه نباید معتبر شمرده شود |
| با تغییر شکل وضعیت یا منطق fold، نسخهٔ قالب را بالا ببرید | snapshot قدیمی قواعد قدیمی را در خود دارد |
| هرگز snapshot جدیدتر را با قدیمیتر بازنویسی نکنید | snapshotگیرهای همزمان با هم مسابقه میدهند |
| snapshot را دورریختنی نگه دارید | بازسازی از رویدادها همیشه ممکن است |
روش استفاده: هر N رویداد یا وقتی زمان بارگذاری از بودجه گذشت، بهشکل ناهمگام snapshot بگیرید؛ SaveSnapshot در Go خودش وضعیت commitشده را دوباره بارگذاری میکند. خطای SQLSTATE 40001 از دو snapshotگیر همزمان را میتوان با خیال راحت نادیده گرفت.
Projection، read model و checkpoint حیاتی
به زبان ساده: projection رویدادها را به ترتیب میخواند و جدولی متناسب با یک پرسش نگه میدارد؛ checkpoint آن آخرین رویداد پردازششده را به یاد دارد.
بدفهمی رایج: «اگر projector رویدادی را نفهمید، ردش کن و ادامه بده.» رد کردن، checkpoint را از روی واقعیتی جلو میبرد که read model هرگز جذبش نکرد؛ خطا حالا دائمی و نامرئی است.
تعریف: read model نسخهای بهینهشده برای query است که از رویدادها مشتق میشود. projection کدی است که آن را نگه میدارد. checkpoint آخرین global position اعمالشده است. درستی سه شرط دارد: ردیفهای read model و checkpoint در یک تراکنش commit شوند؛ هر ردیف نسخهٔ موردانتظار stream را بررسی کند (stream_version = v - 1) و بهروزرسانی دقیقاً یک ردیف را تغییر دهد؛ نوع یا نسخهٔ اسکیمای ناشناخته projector را متوقف کند (Fail closed).
1 Projector -> INSERT checkpoint (balances_v1, 0) ON CONFLICT DO NOTHING
2 Projector -> SELECT position ... FOR UPDATE -> 811 -- second instance waits here
3 Projector -> SELECT events WHERE global_position > 811 LIMIT 500
4 Projector -> 812 MoneyWithdrawn acc-42 v3: UPDATE ... WHERE stream_version = 2 -> 1 row
5 Projector -> UPDATE checkpoint = 812; COMMITسناریوهای واقعی: فهرست حسابها با موجودی؛ داشبورد «سفارشهای در انتظار»؛ ایندکس جستوجو؛ جدول صورتحساب ماهانه. Marten سه چرخهٔ عمر دارد: live aggregation (fold هنگام query)، inline projection (در همان واحد کاریِ append) و async projection که async daemon اجرایش میکند. projectorهای Spatie پس از persist شدن aggregate رویدادها را دریافت میکنند و مستند آن صفی را توصیه میکند که هر بار فقط یک job پردازش کند تا ترتیب حفظ شود.
| چرخهٔ عمر | سازگاری با نوشتن | حالت شکست |
|---|---|---|
| Live (fold هنگام خواندن) | همیشه بهروز | برای streamهای طولانی کند |
| Inline (همان تراکنش) | فوری | باگ projection باعث شکست command میشود |
| Async (با checkpoint) | eventual consistency با تأخیر قابل اندازهگیری | تأخیر، و انحراف اگر بدون بررسی نسخه اعمال شود |
روش استفاده: Project در Go ردیف checkpoint را با ON CONFLICT DO NOTHING درج و سپس قفل میکند، تا دو اجراکنندهٔ بار اول یکدیگر را abort نکنند؛ برابری global_position == checkpoint + 1 را بررسی میکند و با شکاف متوقف میشود. projection نباید اثر جانبی بیرونی داشته باشد؛ projectorی که ایمیل میفرستد، با هر rebuild دوباره میفرستد.
بازسازی و نسخههای blue/green برای projection (Rebuild) مهم
به زبان ساده: برای تغییر یک read model، نسخهٔ جدید را از موقعیت صفر کنار نسخهٔ قدیمی بسازید و بعد خوانندهها را جابهجا کنید.
بدفهمی رایج: «جدول را TRUNCATE کن، checkpoint را صفر کن و replay کن.» در این مدت خوانندهها مدل خالی یا نیمهکاره میبینند و projector زنده هم ممکن است در همان جدول بنویسد.
تعریف: نسخهٔ projection نامی جداگانه است (balances_v1، balances_v2) با ردیفها و checkpoint خودش. نسخهٔ جدید عقبماندگی را جبران میکند در حالی که نسخهٔ قدیمی پاسخ میدهد؛ مرحلهٔ فعالسازی فقط وقتی خوانندهها را به نسخهٔ جدید میبرد که checkpoint آن به head رسیده باشد؛ نسخهٔ قدیمی پس از یک بازهٔ بازگشت (Rollback window) حذف میشود. Marten همین مدل را مستند کرده است: ProjectionVersion را بالا ببرید تا در جدولهای جدا بنویسد و پس از رسیدن، ترافیک را جابهجا کنید.
1 Deploy v2 code -> Project("balances_v2") from 0 while balances_v1 serves
2 v2 checkpoint 0 -> 400000 -> head (head keeps moving)
3 ActivateProjection("balances", "balances_v2", head) -> active_projections updated
4 Readers -> follow active_projections -> v2
5 After rollback window -> stop v1 projector, DELETE rows of balances_v1سناریوهای واقعی: افزودن ستونی که از تاریخچه محاسبه میشود؛ اصلاح باگ projection که جمعهای غلط ساخته بود؛ انتقال read model به پایگاه داده یا موتور جستوجوی دیگر؛ افزودن نوع رویداد جدیدی که projector قدیمی ردش میکند.
| راهبرد | اثر بر خواننده | پیشنیاز |
|---|---|---|
| truncate و replay درجا | مدل خالی یا نیمهکاره در طول rebuild | متوقفکردن نویسندهها، projectorها و خوانندهها |
| نسخههای blue/green | هیچ، تا لحظهٔ جابهجایی | جا برای دو نسخه و مرحلهٔ فعالسازی |
| rebuild برای هر stream | فقط همان stream متأثر میشود | مدل بر اساس stream تقسیم شده باشد |
روش استفاده: ActivateProjection نسخهای را که checkpointاش از موقعیت دادهشده (معمولاً head در لحظهٔ جابهجایی) عقبتر است نمیپذیرد. اثرهای جانبی را مهار کنید: Marten یادآوری میکند نسخهٔ جدیدی که کل تاریخچه را میپیماید، اگر جلویش گرفته نشود اثرهای جانبی را دوباره صادر میکند. Marten گزینهای هم دارد که daemon انواع رویداد ناشناخته را رد کند تا نسخهٔ قدیمی projection در حالی که کد جدید نوع تازهای معرفی میکند به کار ادامه دهد؛ این را استثنایی آگاهانه برای نسخهای بدانید که بهزودی بازنشسته میشود، نه رفتار پیشفرض.
نسخهبندی رویداد و upcasting (Event versioning / Upcaster) حیاتی
به زبان ساده: رویدادهایی که سالها پیش نوشته شدهاند باید همچنان خواندنی باشند. upcaster شکل قدیمی را هنگام خواندن به شکل فعلی تبدیل میکند؛ ردیف ذخیرهشده هرگز تغییر نمیکند.
بدفهمی رایج: «JSON را آسانگیرانه decode کن تا فیلدهای جاافتاده صفر شوند.» برداشتی که چون نام فیلد عوض شده مبلغش صفر خوانده میشود، رویداد قدیمی نیست؛ دادهٔ غلط است.
تعریف: نسخهبندی رویداد به هر رویداد یک نوع و یک نسخهٔ اسکیما میدهد. upcasting تابعی خالص است به شکل (type, version, data) → (type, current version, data) که بین ذخیرهسازی و fold یا projection اعمال میشود. Marten upcasting را تبدیلی توصیف میکند که هر بار هنگام خواندن انجام میشود و سادهترین شکلش تابع است؛ مستند Axon Framework 5.0 میگوید upcasterها هنوز در 5.0 در دسترس نیستند و قرار است برگردند و تا آن زمان تبدیل payload را توصیه میکند؛ یادآوری خوبی برای اینکه نسخهای را که اجرا میکنید بررسی کنید.
1 2024 build -> stores MoneyWithdrawn v1 {"amount_cents": 1250}
2 2026 build -> current MoneyWithdrawn v2 {"amount": 1250, "reason": "..."}
3 Load -> Upcast(v1) -> v2 {"amount": 1250, "reason": "unspecified (v1)"}
4 Load -> MoneyWithdrawn v3 found, build knows only v2 -> ErrUnknownEvent, stopسناریوهای واقعی: فیلدی که نامش عوض شده؛ شکستن یک رویداد به دو رویداد؛ فیلد اجباری جدید با پیشفرض مستند؛ consumerی که در استقرار تدریجی رویداد را از producer جدیدتر میگیرد.
| روش | چه وقت | محدودیت |
|---|---|---|
| افزودن فیلد اختیاری | اطلاعات جدید که خوانندههای قدیمی نادیده میگیرند | فقط اگر خوانندهها فیلد ناشناخته را تحمل کنند |
| upcaster هنگام خواندن | تغییر نام، تغییر ساختار، پیشفرض برای فیلد | باید خالص باشد؛ زنجیره به مرور بلند میشود |
| نوع رویداد جدید | معنا تغییر کرده است | نوع قدیمی همچنان handler میخواهد |
| کپی و تبدیل به store جدید | تغییر ساختاری بزرگ | پروژهٔ migration با جابهجایی خودش |
روش استفاده: بهشکل سختگیرانه decode کنید (DisallowUnknownFields در Go)، upcasterها را کنار تعریف رویدادها با آزمون برای هر نسخهٔ تاریخی نگه دارید و با نوع ناشناخته متوقف شوید. برای تکامل قرارداد بین سرویسها طراحی پیام و تکامل اسکیما را ببینید.
CQRS، با event sourcing یا بدون آن حیاتی
به زبان ساده: یک مدل برای تغییر داده و مدلی دیگر برای خواندن آن.
بدفهمی رایج: «CQRS یعنی دو پایگاه داده، یک broker و eventual consistency.» یادداشت فاولر میگوید دو مدل میتوانند یک پایگاه داده را مشترک داشته باشند؛ هیچ چیز ناهمگامی را اجباری نمیکند.
تعریف: جداسازی مسئولیت فرمان و پرسوجو (Command Query Responsibility Segregation) مدلی را که تغییرات را اعتبارسنجی و اعمال میکند (command، که دادهٔ دامنه برنمیگرداند) از مدلی که به query پاسخ میدهد (و چیزی را تغییر نمیدهد) جدا میکند. با event sourcing مدل query یک projection است؛ بدون آن، مدل query میتواند view در SQL، materialized view یا جدولی باشد که در همان تراکنشِ نوشتن بهروز میشود.
1 POST /accounts/42/withdraw -> command handler -> UPDATE accounts, INSERT ledger_lines; COMMIT
2 Same transaction -> UPDATE account_summary (query model)
3 GET /accounts/42/summary -> query handler -> SELECT FROM account_summary
4 No events stored, no broker, no lag: still CQRSسناریوهای واقعی: مدل نوشتن با اعتبارسنجی غنی و یک جدول گزارش تخت؛ صفحهٔ فهرستی که شش جدول را join میکرد و با یک جدول denormalized جایگزین شد؛ ایندکس جستوجویی که از مدل نوشتن تغذیه میشود؛ پایگاه دادهٔ گزارشگیری (ReportingDatabase به تعبیر فاولر) برای تحلیلگران.
| گونه | مدل query | سازگاری |
|---|---|---|
| یک مدل با رابطهای جدا | همان جدولها | فوری |
| یک پایگاه داده، جدولهای جدا | view، materialized view یا جدول در همان تراکنش | فوری یا مبتنی بر refresh |
| store جدا که از رویدادها ساخته میشود | projection | eventual consistency با token برای read-your-writes |
روش استفاده: در یک monolith با handlerها و query objectهای جدا شروع کنید؛ فقط وقتی شکل یا بار query توجیهش کرد store جدا اضافه کنید. هشدار فاولر برقرار است: بیشتر سیستمها با CRUD جورند و CQRS مال bounded contextهای مشخص است.
توکن خواندن نوشتههای خود (Read-your-writes token) مهم
به زبان ساده: کلاینت پس از نوشتن یک موقعیت میگیرد؛ query فقط وقتی پاسخ میدهد که read model به آن موقعیت رسیده باشد.
بدفهمی رایج: «قبل از redirect دویست میلیثانیه صبر کن.» تأخیر زیر بار و در زمان rebuild هیچ سقفی ندارد.
تعریف: Execute مقدار LastPosition را برمیگرداند. QueryBalance(account, atLeast) checkpoint نسخهٔ فعال projection را در همان دستورِ خواندن ردیف میخواند؛ اگر checkpoint از token کمتر باشد ErrStale برمیگرداند و فراخواننده صبر میکند (WaitForPosition)، پیام «در حال بهروزرسانی» نشان میدهد یا از مدل نوشتن (Load) پاسخ میدهد.
1 Client -> Execute(withdraw) -> {version 3, position 812}
2 Client -> GET /balance?atLeast=812
3 Query -> checkpoint 805 < 812 -> ErrStale
4 Query -> WaitForPosition(812, 50 ms ticks, 2 s deadline) -> checkpoint 812
5 Query -> balance 70, AsOf 812سناریوهای واقعی: «سفارش تازهام در صفحهٔ سفارشها نیست»؛ موجودیای که پیش از انتقالِ همین حالا نمایش داده میشود؛ آزمونی که درست پس از command، projection را بررسی میکند. Marten برای آزمونها WaitForNonStaleProjectionDataAsync را با همین ایده دارد.
| گزینه | تازگی | هزینه |
|---|---|---|
| token و انتظار | نوشتههای خود تضمینشده | تأخیر اضافه هنگام عقبماندگی |
| token و بازگشت به مدل نوشتن | تضمینشده | بار روی سمت نوشتن |
| inline projection | فوری | شکست projection یعنی شکست command |
| بدون token | eventual consistency | کاربر سردرگم |
روش استفاده: token را در header یا cookie پاسخ حمل کنید؛ برای replicaها همین ایده روی موقعیت replication اعمال میشود، ببینید replication و failover.
idempotency فرمان و رسید (Command receipt) حیاتی
به زبان ساده: اگر پاسخ «۳۰ برداشت کن» گم شد، کلاینت همان فرمان را با همان ID دوباره میفرستد؛ store از روی رسید پاسخ میدهد و دو بار برداشت نمیکند.
بدفهمی رایج: «expected version تکرار را امن میکند.» تکرار پس از گمشدن تأیید COMMIT نسخهٔ موردانتظار ۲ را دارد در حالی که store در ۳ است: CAS ردش میکند، کلاینت دوباره بارگذاری میکند، موجودی ۷۰ را میبیند و دوباره برداشت میکند. CAS جلوی بازنویسی همزمان را میگیرد، نه تکرار یک نیت را.
تعریف: command receipt شناسهٔ فرمان، یک fingerprint (هش SHA-256 نیت) و نتیجه را در همان تراکنش رویدادها ذخیره میکند. با تکرار با همان ID و همان fingerprint، نتیجهٔ ذخیرهشده با Duplicate=true برمیگردد؛ همان ID با fingerprint متفاوت خطای ErrCommandIDReused میدهد.
1 Client -> Execute(c-77, withdraw 30, expected v2) -> COMMIT succeeds
2 Network -> response lost; client sees ErrCommitUnknown or a timeout
3 Client -> Execute(c-77, withdraw 30, expected v2) again
4 Execute -> receipt c-77 found, fingerprint equal -> {v3, 812, Duplicate}
5 Client -> Execute(c-77, withdraw 50) -> ErrCommandIDReusedسناریوهای واقعی: timeout کلاینت HTTP؛ worker صفی که پس از commit و پیش از تأیید پیامش از کار افتاد؛ webhook درگاه پرداخت که دو بار تحویل شد.
| لایه | سازوکار | پوشش میدهد |
|---|---|---|
| سمت command | command receipt در تراکنش append | فرمانهای تکراری |
| Projection | checkpoint و بررسی نسخهٔ stream | دستههای replayشده |
| consumer پاییندست | inbox بر اساس event ID یا نسخهٔ stream | تحویل دوبارهٔ broker؛ ببینید مصرفکنندهٔ idempotent |
| producer در broker | idempotent producer در Kafka، deduplication در RabbitMQ Streams، deduplication در SQS FIFO | تکرار producer در محدودهٔ خود broker |
روش استفاده: بگذارید کلاینت command ID را بسازد (یک UUID برای هر نیت کاربر که در هر تکرار دوباره استفاده میشود)؛ رسیدها را دستکم به اندازهٔ مدتی نگه دارید که کلاینت ممکن است تکرار کند؛ تصمیم بگیرید فرمانهای ردشده هم رسید بگیرند یا نه.
زمان رویداد، زمان پردازش، اصلاح و رویداد جبرانی (Event time / Processing time / Compensating event) مهم
به زبان ساده: رویداد ثبت میکند چیزی کی اتفاق افتاد (event time) و سیستم کی از آن باخبر شد (processing time)؛ واقعیت غلط با واقعیت جدید اصلاح میشود، نه با ویرایش قبلی.
بدفهمی رایج: «بر اساس occurred_at مرتب کن.» رویدادهای دیررس (پایانهٔ کارت آفلاینی که فردا همگام میشود) زمان رویداد قدیمی و موقعیت جدید دارند. موقعیت ترتیب پردازش را میدهد؛ زمان رویداد داده است.
تعریف: occurred_at زمان رویداد است که کسبوکار یا دستگاه میدهد؛ recorded_at زمان پردازش است که store تعیین میکند. رویداد جبرانی (همان reversal transaction گرگ یانگ) مثل WithdrawalReversed به رویداد اصلی ارجاع میدهد و اثرش را خنثی میکند و ردّ آن را باقی میگذارد. مقالهٔ فاولر برای حالت سختترِ تغییر آنچه در گذشته باور داشتیم، رویداد عطفبهماسبق (Retroactive event) و طراحی دوزمانه (Bi-temporal) را بررسی میکند.
1 Day 1 10:00 -> MoneyWithdrawn e-55 {30}, occurred 10:00, recorded 10:00
2 Day 2 09:00 -> dispute: duplicate card charge
3 Day 2 09:05 -> WithdrawalReversed {withdrawal_event_id: e-55, amount: 30}, recorded day 2
4 Statement for day 1 (event time) -> shows the withdrawal; balance today (position order) -> restoredسناریوهای واقعی: chargeback؛ قیمتی که با ممیز اشتباه وارد شد؛ مرسولهای که دو بار اسکن شد؛ خوانش دیررس یک حسگر. پنجرهبندی بر اساس زمان رویداد مال پردازش جریان است.
| نیاز | سازوکار |
|---|---|
| خنثیکردن یک اثر | رویداد جبرانی با ارجاع به رویداد اصلی |
| اصلاح یک مقدار | رویداد اصلاحی با مقدار جدید و دلیل |
| گزارش «آنطور که میدانستیم» | فیلتر بر اساس recorded_at یا موقعیت |
| گزارش «آنطور که رخ داد» | فیلتر بر اساس occurred_at |
روش استفاده: Decide در Go برگشت را فقط برای برداشتی موجود و هنوز برگشتنخورده با همان مبلغ میپذیرد؛ برگشت دوباره شکست میخورد.
حریم خصوصی و حذف در لاگ تغییرناپذیر (Crypto-shredding / Tombstone) مهم
به زبان ساده: دادهٔ شخصی را بهصورت متن ساده در رویدادهایی که هرگز تغییر نمیکنند ذخیره نکنید؛ آن را با کلیدی مخصوص هر فرد رمز کنید و وقتی داده باید برود، کلید را نابود کنید.
بدفهمی رایج: «crypto-shredding ما را منطبق با قانون میکند.» این کار فقط خوانایی فیلدهای مُهرشده را در همین store از بین میبرد؛ پشتیبان جدول کلیدها، replicaها، لاگها، cacheها، read modelها، ایندکسهای جستوجو و topicهای brokerی که متن ساده گرفتهاند، کپیهای جداگانهاند. الزامات قانونی بررسی حقوقی میخواهد.
تعریف: در crypto-shredding فیلدهای حساس با کلیدی مخصوص هر صاحب داده مُهر میشوند (اینجا AES-256-GCM و شناسهٔ صاحب داده بهعنوان associated data)؛ حذف کلید (ForgetSubject) همهٔ مقدارهای مُهرشده را ناخوانا میکند در حالی که ردیف رویدادها میماند. tombstone نشانهٔ حذف است: hard delete در KurrentDB یک tombstone با نوع $streamDeleted اضافه میکند و استفادهٔ دوباره از stream را میبندد، در حالی که soft delete مقدار TruncateBefore را تنظیم میکند و scavenging بعداً رویدادها را پاک میکند؛ در Kafka، tombstone رکوردی با key و مقدار null است که compaction با آن مقدارهای قبلی همان key را حذف میکند.
1 Open account -> SubjectKey(sub-9) -> Seal("Ada Example") -> AccountOpened.owner_name_sealed
2 Read -> RevealOwnerName -> key found -> "Ada Example"
3 Erasure request -> ForgetSubject(sub-9) -> DELETE subject_keys
4 Read -> ErrShredded; fold still works (no balance data was sealed)
5 Read models / search index -> must delete their plaintext copies separatelyسناریوهای واقعی: درخواست حذف دادهٔ مشتریای که حسابش بسته شده؛ قاعدهٔ نگهداری برای مدارک احراز هویت؛ ابزار پشتیبانی که نباید نامها را به بیشتر کارکنان نشان دهد.
| Store | ابزار حذف | نکته |
|---|---|---|
| جدول رویداد در PostgreSQL | crypto-shredding؛ یا DELETE بازبینیشده با غیرفعالکردن trigger | پشتیبانها و replicaها صفحههای قدیمی را نگه میدارند |
| KurrentDB | soft delete (TruncateBefore) یا hard delete (tombstone) بههمراه scavenging | خوانندههای $all رویدادهای scavengeنشده را میبینند |
| Kafka | tombstone در compaction، retention | consumerها و کپیهای بیرون از Kafka |
| Redis Streams | XDEL، XTRIM | فایلهای AOF/RDB و replicaها |
روش استفاده: فقط چیزی را مُهر کنید که باید قابل حذف باشد؛ fold را مستقل از فیلدهای مُهرشده نگه دارید؛ در محیط واقعی کلیدهای داده را با KMS بپیچید؛ فهرست همهٔ کپیها را داشته باشید. بحث عمیقتر: امنیت پیامرسانی.
Log compaction در Kafka و محدودیتهایش مهم
به زبان ساده: compaction جدیدترین رکورد هر key را نگه میدارد و قبلیها را دور میریزد. این snapshotی از آخرین مقدارهاست، نه تاریخچه.
بدفهمی رایج: «topic فشردهشده با key شناسهٔ حساب، event store ماست.» پس از compaction فقط آخرین رویداد هر حساب میماند؛ یک واریز و سپس یک برداشت تبدیل میشود به فقط همان برداشت.
تعریف: مستند طراحی Kafka تضمین میکند که compaction دستکم آخرین مقدار شناختهشدهٔ هر key را در یک partition نگه میدارد، ترتیب را عوض نمیکند، offsetها را تغییر نمیدهد و consumerی که از ابتدا شروع کند وضعیت نهایی هر key را میبیند؛ delete.retention.ms مدت دیدهشدن tombstoneها و min.compaction.lag.ms مدت فشردهنشدن head را محدود میکند. مقدار پیشفرض cleanup.policy برابر delete است.
1 account-events (cleanup.policy=compact), key A: 0 opened, 2 +100, 3 -30, 5 +30
2 Log cleaner runs -> key A keeps offset 5 (+30) only
3 New projector replays from offset 0 -> sees "+30" for A -> balance 30, truth 100سناریوهای واقعی: topic فشردهشدهٔ «آخرین موجودی هر حساب» (event-carried state) انتخاب خوبی است؛ topic فشردهشدهٔ «رویدادهای حساب» نه؛ key یکتا برای هر رویداد از گمشدن جلوگیری میکند اما آن وقت compaction چیزی حذف نمیکند و فقط topicی با نگهداری نامحدود دارید.
| هدف topic | cleanup.policy | replay از ابتدا چه میدهد |
|---|---|---|
| انتقال رویداد، پایگاه داده store است | delete با retention | فقط رویدادهای اخیر |
| آخرین وضعیت هر key | compact | مقدار نهایی هر key و tombstoneها در بازهٔ delete.retention.ms |
| هر دو | delete,compact | segmentهای فشردهشده تا وقتی retention حذفشان کند |
روش استفاده: تاریخچه را در event store نگه دارید؛ برای وضعیت از topic فشردهشده استفاده کنید؛ بستهٔ kafkarelay در Go هر دو پیکربندی را صریح تعریف کرده است.
سازوکار و کنترلهای دقیق
تراکنش append قدمبهقدم حیاتی
BEGIN; -- READ COMMITTED
SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE; -- 812, held to COMMIT
SELECT fingerprint, stream_version, last_position
FROM command_receipts WHERE command_id = 'c-77'; -- no row: new command
SELECT version FROM streams WHERE id = 'acc-42'; -- 2
SELECT version, format, state FROM snapshots WHERE stream_id = 'acc-42';
SELECT ... FROM events WHERE stream_id = 'acc-42' AND stream_version > 0 ORDER BY stream_version;
UPDATE streams SET version = 3 WHERE id = 'acc-42' AND version = 2; -- must be 1 row
INSERT INTO events (global_position, event_id, stream_id, stream_version, type,
schema_version, data, command_id, occurred_at)
VALUES (812, 'c-77/0', 'acc-42', 3, 'MoneyWithdrawn', 2,
'{"amount":30,"reason":"atm"}', 'c-77', '2026-11-26T10:00:00Z');
UPDATE feed_allocator SET next_position = 813 WHERE id = 1;
INSERT INTO command_receipts VALUES ('c-77', 'acc-42', '9f2c...', 3, 812, now());
COMMIT;| کنترل یا نشانه | معنا |
|---|---|
FOR UPDATE روی feed_allocator | appendها را سریالی میکند؛ قفل با COMMIT یا ROLLBACK آزاد میشود |
UPDATE ... WHERE version = $expected با صفر ردیف | expected version اشتباه است |
SQLSTATE 23505 یعنی unique_violation | پشتیبان UNIQUE (stream_id, stream_version) یا event_id عمل کرده است |
SQLSTATE 40001 یعنی serialization_failure | نویسندهٔ snapshot در REPEATABLE READ مسابقه داده؛ تکرار یا رد کنید |
SQLSTATE 40P01 یعنی deadlock_detected | با یک ترتیب قفل نباید رخ دهد؛ بررسی کنید |
trigger با نام events_append_only | UPDATE، DELETE و TRUNCATE روی events خطا میدهند |
ErrCommitUnknown | COMMIT خطا داد؛ با همان command ID تکرار کنید |
lock_timeout / statement_timeout | سقف انتظار روی allocator در زمان رخداد |
بارگذاری، snapshot و projection زیر سطح جداسازی مهم
Load از تراکنش فقطخواندنی REPEATABLE READ استفاده میکند: مستند PostgreSQL میگوید این سطح فقط دادهای را میبیند که پیش از شروع تراکنش commit شده باشد؛ پس streams.version، snapshot و دنباله حتی وقتی appendها ادامه دارند یک دید سازگارند. درون Execute قفل allocator از قبل جلوی appendها را میگیرد، پس Read Committed کافی است. projectorها با Read Committed اجرا میشوند و به ترتیب commitِ allocator تکیه دارند: هر موقعیتی که ببینند، همسایهٔ کوچکترِ نامرئی ندارد. برای ناهنجاریهای پشت این انتخابها سطوح جداسازی را ببینید.
| عملیات | سطح جداسازی | قفلها | شکست موردانتظار |
|---|---|---|---|
Execute | Read Committed | ردیف allocator با FOR UPDATE | expected version اشتباه، خطای دامنه، commit نامعلوم |
Load | Repeatable Read فقطخواندنی | ندارد | تاریخچهٔ خراب (ErrCorruptHistory) |
SaveSnapshot | Repeatable Read | ردیف snapshot هنگام upsert | خطای 40001 از snapshot همزمان |
Project | Read Committed | ردیف checkpoint با FOR UPDATE | شکاف feed، انحراف، رویداد ناشناخته |
ActivateProjection | Read Committed | checkpoint با FOR SHARE | هنوز نرسیده است |
راهحل مشکلات کلاسیک
نویسندههای همزمان روی یک stream
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| CAS روی expected version | UPDATE streams ... WHERE version = v | هنگام تصمیمگیری بیرون از store قفلی نگه داشته نمیشود | تکرار زیر رقابت شدید |
| قفل بدبینانهٔ stream | SELECT ... FROM streams FOR UPDATE پیش از تصمیم | تکرار لازم نیست | انتظار قفل و deadlock بین streamها |
| یک نویسنده برای هر stream | فرمانهای یک key به یک worker میروند | ساده و مرتب | طراحی مسیریابی و failover |
| قفل سراسری allocator (این store) | هر بار فقط یک appender | feed مرتب به ترتیب commit بدون هزینهٔ اضافه | appendهای سریالی |
projectionهایی که نه گم میکنند نه دو بار اعمال میکنند
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| ردیفها و checkpoint در یک تراکنش | مدل و checkpoint در یک پایگاه داده | اثر دقیقاً یکباره روی مدل | مدل باید در همان پایگاه داده باشد |
| upsert idempotent بر اساس نسخهٔ stream | WHERE stream_version = v - 1 | بین پایگاههای داده هم کار میکند | هر ردیف نسخه میخواهد |
| inbox از event IDها | پیش از اعمال، event ID درج شود | عمومی | رشد جدول و پاکسازی |
| fail closed | با ناشناخته، شکاف یا انحراف متوقف شو | خطا نمایان میماند | تأخیر تا رفع مشکل |
نتیجهٔ نامعلوم commit و تکرار
| راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|
| command receipt و fingerprint | نتیجه همراه رویدادها ذخیره شود | پاسخ دقیق هنگام تکرار | مدت نگهداری رسید |
| event ID قطعی | command_id/index با UNIQUE (event_id) | درج تکراری شکست میخورد | نتیجهٔ اصلی را برنمیگرداند |
| idempotency طبیعی | فرمانهایی مثل «نشانی را X کن» | ذخیرهسازی لازم نیست | برای پول بهندرت صادق است |
یکپارچهسازی با سرویسهای دیگر
event store خودبهخود یک outbox مطمئن برای یکپارچهسازی نیست: relayها باید feed مرتب به ترتیب commit را با checkpoint دنبال کنند، با تأیید broker منتشر کنند و رویدادهای داخلی را به قراردادهای عمومی پایدار نگاشت دهند، بهجای اینکه همهٔ فیلدهای داخلی را بیرون بریزند. RelayOnce checkpoint خود را فقط تا آخرین رویداد تأییدشده جلو میبرد و با اولین شکست یا شکاف میایستد؛ تحویل at-least-once است.
انتخاب
| موقعیت | پیشنهاد | روش تکمیلی | دلیل |
|---|---|---|---|
| صفحههای مدیریتی CRUD با قواعد ساده | هیچکدام | در صورت نیاز جدول ممیزی | کمترین هزینه؛ هشدار فاولر |
| queryهای پیچیده روی نوشتنهای ساده | CQRS بدون event sourcing | view یا جدول خلاصه در همان تراکنش | مدل query بدون ماشینآلات رویداد |
| ممیزی، اعتراض، «چرا اینطور است» | event sourcing برای همان bounded context | receipt و رویداد جبرانی | تاریخچه خودِ نیازمندی است |
| شکلهای خواندن فراوان از یک تاریخچه | event sourcing با projection ناهمگام | rebuild به روش blue/green و token | مدلهای قابل بازسازی |
| قواعد سخت برای هر موجودیت و رقابت شدید روی یک موجودیت | event sourcing فقط اگر رقابت با تکرار جور شود | یک نویسنده برای هر stream | تکرارهای CAS ممکن است غالب شوند |
| payloadهای بزرگ با دادهٔ شخصی | در رویداد نگذارید | crypto-shredding و ارجاع | حذف ممکن میماند |
| توان عملیاتی بیش از یک appender سریالی | KurrentDB، تشخیص شکاف به سبک Marten یا CDC | اول اندازه بگیرید | قفل allocator سقف دارد |
| تیمی که با الگو تازه آشنا شده | با یک context شروع کنید | اول inline projection | منحنی یادگیری عملیاتی |
چه وقت این کار را نکنیم: دامنه تاریخچهٔ معناداری ندارد؛ گزارشها به SQL موردی روی وضعیت فعلی نیاز دارند؛ کسی projection و rebuild را اداره نمیکند؛ حذف قانونی بیشتر دادهها مکرر است؛ یا تیم فقط برای رزومه میخواهدش. event sourcing تصمیمی برای هر context است، نه معماری کل یک شرکت.
Go
Before
یک بهروزرسانی سادهٔ موجودی. اتمیک است و جلوی منفیشدن را میگیرد، اما پس از COMMIT تاریخچه، دلیل و ترتیب از بین رفتهاند.
// Package before keeps only the current balance. It works, and it is the
// right design for many systems, but it cannot answer "how did we get here?".
package before
import (
"context"
"database/sql"
"errors"
)
var ErrInsufficientFunds = errors.New("insufficient funds")
// Withdraw overwrites the balance in place. The previous value, the reason
// and the order of changes are gone after COMMIT; an audit log written
// separately can disagree with this row, and a mistaken withdrawal can only
// be "fixed" by editing the number again.
func Withdraw(ctx context.Context, db *sql.DB, accountID string, amount int64) error {
res, err := db.ExecContext(ctx,
`UPDATE accounts SET balance = balance - $2, updated_at = now()
WHERE id = $1 AND balance >= $2 AND $2 > 0`, accountID, amount)
if err != nil {
return err
}
if n, err := res.RowsAffected(); err != nil {
return err
} else if n != 1 {
return ErrInsufficientFunds
}
return nil
}After
لایهٔ دامنه: decode سختگیرانه، مبلغ مثبت، بررسی سرریز، محافظهای حالت، برگشت جبرانی و Apply قطعی که با تاریخچهٔ ناسازگار شکست میخورد.
package es
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"regexp"
"time"
)
// Domain errors. They reject a command; nothing is appended.
var (
ErrInvalidCommand = errors.New("invalid command")
ErrInvalidAmount = errors.New("amount must be positive")
ErrOverflow = errors.New("balance would overflow")
ErrAlreadyOpen = errors.New("account already open")
ErrNotOpen = errors.New("account not open")
ErrInsufficientFunds = errors.New("insufficient funds")
ErrUnknownWithdrawal = errors.New("withdrawal unknown or already reversed")
)
// ErrCorruptHistory means stored events contradict each other. Loading stops.
var ErrCorruptHistory = errors.New("corrupt or inconsistent history")
// Account is the write-side state folded from one stream. It is also the
// snapshot shape, so a change here must bump SnapshotFormat.
type Account struct {
ID string `json:"id"`
Version int64 `json:"version"`
Opened bool `json:"opened"`
Currency string `json:"currency"`
Balance int64 `json:"balance"`
Withdrawals map[string]int64 `json:"withdrawals"` // reversible, by event ID
}
// NewAccount is the empty state before the first event.
func NewAccount(id string) Account {
return Account{ID: id, Withdrawals: map[string]int64{}}
}
// Apply folds one upcast event. It is deterministic and performs no I/O; it
// fails only when history is inconsistent or unsupported.
func (a *Account) Apply(e Event) error {
if e.StreamID != a.ID || e.StreamVersion != a.Version+1 {
return fmt.Errorf("%w: %s v%d after v%d", ErrCorruptHistory, e.StreamID, e.StreamVersion, a.Version)
}
if (e.Type == TypeAccountOpened) == a.Opened {
return fmt.Errorf("%w: %s at v%d", ErrCorruptHistory, e.Type, e.StreamVersion)
}
switch e.Type {
case TypeAccountOpened:
var p AccountOpened
if err := decodeStrict(e.Data, &p); err != nil || !currencyCode.MatchString(p.Currency) {
return fmt.Errorf("%w: bad AccountOpened %s", ErrCorruptHistory, e.EventID)
}
a.Opened, a.Currency = true, p.Currency
case TypeMoneyDeposited:
var p MoneyDeposited
if err := decodeStrict(e.Data, &p); err != nil {
return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
}
if err := a.credit(p.Amount); err != nil {
return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
}
case TypeMoneyWithdrawn:
var p MoneyWithdrawn
if err := decodeStrict(e.Data, &p); err != nil {
return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
}
if p.Amount <= 0 || p.Amount > a.Balance {
return fmt.Errorf("%w: withdrawal %d with balance %d", ErrCorruptHistory, p.Amount, a.Balance)
}
a.Balance -= p.Amount
a.Withdrawals[e.EventID] = p.Amount
case TypeWithdrawalReversed:
var p WithdrawalReversed
if err := decodeStrict(e.Data, &p); err != nil {
return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
}
if amt, ok := a.Withdrawals[p.WithdrawalEventID]; !ok || amt != p.Amount {
return fmt.Errorf("%w: reversal of %s", ErrCorruptHistory, p.WithdrawalEventID)
}
if err := a.credit(p.Amount); err != nil {
return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
}
delete(a.Withdrawals, p.WithdrawalEventID)
default:
return fmt.Errorf("%w: %s", ErrUnknownEvent, e.Type)
}
a.Version = e.StreamVersion
return nil
}
func (a *Account) credit(amount int64) error {
if amount <= 0 {
return ErrInvalidAmount
}
if a.Balance > math.MaxInt64-amount {
return ErrOverflow
}
a.Balance += amount
return nil
}
// Command kinds.
const (
KindOpen = "open"
KindDeposit = "deposit"
KindWithdraw = "withdraw"
KindReverse = "reverse"
)
// Expected-version sentinels, in the style of KurrentDB's stream states.
const (
AnyVersion int64 = -1 // no concurrency check
NoStream int64 = 0 // the stream must not exist yet
)
// Command is an intent. CommandID is chosen by the client and reused on every
// retry of the same intent.
type Command struct {
CommandID string `json:"-"`
StreamID string `json:"stream_id"`
ExpectedVersion int64 `json:"expected_version"`
Kind string `json:"kind"`
Amount int64 `json:"amount,omitempty"`
Currency string `json:"currency,omitempty"`
Reason string `json:"reason,omitempty"`
TargetEventID string `json:"target_event_id,omitempty"`
SubjectID string `json:"subject_id,omitempty"`
OwnerNameSealed []byte `json:"owner_name_sealed,omitempty"`
OccurredAt time.Time `json:"occurred_at"`
}
var currencyCode = regexp.MustCompile(`^[A-Z]{3}$`)
// Fingerprint hashes everything except the command ID. Reusing an ID with a
// different intent is a client bug, not a retry.
func (c Command) Fingerprint() (string, error) {
b, err := json.Marshal(c)
if err != nil {
return "", err
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
func (c Command) validate() error {
if c.CommandID == "" || c.StreamID == "" || c.OccurredAt.IsZero() || c.ExpectedVersion < AnyVersion {
return fmt.Errorf("%w: id, stream, occurred_at and expected version are required", ErrInvalidCommand)
}
return nil
}
// Pending is an event decided but not yet stored.
type Pending struct {
Type string
Data json.RawMessage
OccurredAt time.Time
}
// Decide checks a command against current state and returns the events to
// append. It is pure: same state and command, same answer.
func Decide(a Account, c Command) ([]Pending, error) {
if err := c.validate(); err != nil {
return nil, err
}
var payload any
var typ string
switch c.Kind {
case KindOpen:
if a.Opened {
return nil, ErrAlreadyOpen
}
if !currencyCode.MatchString(c.Currency) || c.SubjectID == "" {
return nil, fmt.Errorf("%w: currency and subject are required", ErrInvalidCommand)
}
typ, payload = TypeAccountOpened, AccountOpened{Currency: c.Currency, SubjectID: c.SubjectID, OwnerNameSealed: c.OwnerNameSealed}
case KindDeposit, KindWithdraw, KindReverse:
if !a.Opened {
return nil, ErrNotOpen
}
if c.Amount <= 0 {
return nil, ErrInvalidAmount
}
switch c.Kind {
case KindDeposit:
if a.Balance > math.MaxInt64-c.Amount {
return nil, ErrOverflow
}
typ, payload = TypeMoneyDeposited, MoneyDeposited{Amount: c.Amount}
case KindWithdraw:
if c.Amount > a.Balance {
return nil, ErrInsufficientFunds
}
typ, payload = TypeMoneyWithdrawn, MoneyWithdrawn{Amount: c.Amount, Reason: c.Reason}
default:
if amt, ok := a.Withdrawals[c.TargetEventID]; !ok || amt != c.Amount {
return nil, ErrUnknownWithdrawal
}
if a.Balance > math.MaxInt64-c.Amount {
return nil, ErrOverflow
}
typ, payload = TypeWithdrawalReversed, WithdrawalReversed{WithdrawalEventID: c.TargetEventID, Amount: c.Amount, Reason: c.Reason}
}
default:
return nil, fmt.Errorf("%w: kind %q", ErrInvalidCommand, c.Kind)
}
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
return []Pending{{Type: typ, Data: data, OccurredAt: c.OccurredAt}}, nil
}رویدادها، نسخههای اسکیما و upcasterی که در برابر ناشناخته میایستد:
// Package es is a small PostgreSQL event store built only on database/sql.
// The host program opens *sql.DB with a PostgreSQL driver (for example the
// pgx stdlib adapter) and applies ../sql/schema.sql first.
package es
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"time"
)
// Event is one stored fact. StreamVersion orders a single stream;
// GlobalPosition orders the whole store in commit order without gaps.
type Event struct {
EventID string
StreamID string
StreamVersion int64
GlobalPosition int64
Type string
SchemaVersion int
Data json.RawMessage
CommandID string
OccurredAt time.Time // event time, supplied by the business
RecordedAt time.Time // processing time, assigned by the store
}
// Event types and their current schema versions.
const (
TypeAccountOpened = "AccountOpened"
TypeMoneyDeposited = "MoneyDeposited"
TypeMoneyWithdrawn = "MoneyWithdrawn"
TypeWithdrawalReversed = "WithdrawalReversed"
)
var currentSchema = map[string]int{
TypeAccountOpened: 1,
TypeMoneyDeposited: 1,
TypeMoneyWithdrawn: 2,
TypeWithdrawalReversed: 1,
}
// ErrUnknownEvent is returned for a type or schema version this build cannot
// interpret. Readers stop instead of skipping, so nothing is silently lost.
var ErrUnknownEvent = errors.New("unknown event type or schema version")
// Payloads of the current schema versions.
type AccountOpened struct {
Currency string `json:"currency"`
SubjectID string `json:"subject_id"`
OwnerNameSealed []byte `json:"owner_name_sealed"` // see shred.go
}
type MoneyDeposited struct {
Amount int64 `json:"amount"`
}
type MoneyWithdrawn struct {
Amount int64 `json:"amount"`
Reason string `json:"reason"`
}
type WithdrawalReversed struct {
WithdrawalEventID string `json:"withdrawal_event_id"`
Amount int64 `json:"amount"`
Reason string `json:"reason"`
}
// moneyWithdrawnV1 is the historical shape: no reason, differently named amount.
type moneyWithdrawnV1 struct {
AmountCents int64 `json:"amount_cents"`
}
// Upcast converts a stored event to the current schema version on read.
// Stored rows are never rewritten.
func Upcast(e Event) (Event, error) {
want, known := currentSchema[e.Type]
if !known {
return Event{}, fmt.Errorf("%w: %s v%d", ErrUnknownEvent, e.Type, e.SchemaVersion)
}
if e.Type == TypeMoneyWithdrawn && e.SchemaVersion == 1 {
var old moneyWithdrawnV1
if err := decodeStrict(e.Data, &old); err != nil {
return Event{}, fmt.Errorf("upcast %s: %w", e.EventID, err)
}
data, err := json.Marshal(MoneyWithdrawn{Amount: old.AmountCents, Reason: "unspecified (v1)"})
if err != nil {
return Event{}, err
}
e.Data, e.SchemaVersion = data, 2
return e, nil
}
if e.SchemaVersion != want {
return Event{}, fmt.Errorf("%w: %s v%d", ErrUnknownEvent, e.Type, e.SchemaVersion)
}
return e, nil
}
// decodeStrict rejects unknown fields and trailing data, so a payload from a
// newer producer is not half-read by an older consumer.
func decodeStrict(data []byte, v any) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
return err
}
if dec.More() {
return errors.New("trailing data after JSON value")
}
return nil
}store: قفل allocator، رسید، CAS، append و اعتبارسنجی snapshot.
package es
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
)
// Store errors.
var (
// ErrWrongExpectedVersion: the stream moved since the caller read it.
// Reload, decide again, retry with a NEW expected version but the SAME command ID.
ErrWrongExpectedVersion = errors.New("wrong expected version")
// ErrCommandIDReused: the ID was already used for a different intent.
ErrCommandIDReused = errors.New("command ID reused with a different intent")
// ErrCommitUnknown: COMMIT returned an error; the append may or may not
// exist. Retry the same command; its receipt reveals the outcome.
ErrCommitUnknown = errors.New("commit outcome unknown")
)
// SnapshotFormat versions the Account JSON and the fold rules behind it.
// Snapshots with another format are ignored and the stream is replayed.
const SnapshotFormat = 1
// Result is returned for a stored command and for its retries.
type Result struct {
StreamVersion int64
LastPosition int64 // read-your-writes token for the query side
Duplicate bool // answered from the command receipt
}
// Store is safe for concurrent use; all appends go through Execute.
type Store struct{ db *sql.DB }
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
type querier interface {
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
// Execute decides and appends atomically: allocator lock, receipt check,
// expected-version CAS, events, allocator advance, receipt, COMMIT.
func (s *Store) Execute(ctx context.Context, cmd Command) (Result, error) {
if err := cmd.validate(); err != nil {
return Result{}, err
}
fp, err := cmd.Fingerprint()
if err != nil {
return Result{}, err
}
tx, err := s.db.BeginTx(ctx, nil) // READ COMMITTED
if err != nil {
return Result{}, err
}
defer tx.Rollback()
// The row lock is held until COMMIT. The next appender cannot read
// next_position before this transaction is visible, so positions become
// visible in allocation order and an aborted append leaves no gap.
// Cost: appends to ALL streams are serialized.
var next int64
if err := tx.QueryRowContext(ctx,
`SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE`).Scan(&next); err != nil {
return Result{}, fmt.Errorf("lock feed allocator: %w", err)
}
// Safe without races: no other append runs while we hold the lock.
var prevFP string
var r Result
err = tx.QueryRowContext(ctx,
`SELECT fingerprint, stream_version, last_position FROM command_receipts WHERE command_id = $1`,
cmd.CommandID).Scan(&prevFP, &r.StreamVersion, &r.LastPosition)
switch {
case err == nil && prevFP == fp:
r.Duplicate = true
return r, nil
case err == nil:
return Result{}, ErrCommandIDReused
case !errors.Is(err, sql.ErrNoRows):
return Result{}, err
}
acc, err := load(ctx, tx, cmd.StreamID)
if err != nil {
return Result{}, err
}
if cmd.ExpectedVersion != AnyVersion && acc.Version != cmd.ExpectedVersion {
return Result{}, fmt.Errorf("%w: expected %d, stream at %d", ErrWrongExpectedVersion, cmd.ExpectedVersion, acc.Version)
}
pending, err := Decide(acc, cmd)
if err != nil {
return Result{}, err
}
newVersion := acc.Version + int64(len(pending))
// Compare-and-set on the stream head. Redundant while every writer takes
// the allocator lock, but it keeps the invariant if one does not.
var res sql.Result
if acc.Version == 0 {
res, err = tx.ExecContext(ctx,
`INSERT INTO streams (id, version) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING`, cmd.StreamID, newVersion)
} else {
res, err = tx.ExecContext(ctx,
`UPDATE streams SET version = $2 WHERE id = $1 AND version = $3`, cmd.StreamID, newVersion, acc.Version)
}
if err := oneRow(res, err); err != nil {
return Result{}, fmt.Errorf("%w: stream head moved: %v", ErrWrongExpectedVersion, err)
}
for i, p := range pending {
e := Event{
EventID: fmt.Sprintf("%s/%d", cmd.CommandID, i),
StreamID: cmd.StreamID,
StreamVersion: acc.Version + 1 + int64(i),
GlobalPosition: next + int64(i),
Type: p.Type,
SchemaVersion: currentSchema[p.Type],
Data: p.Data,
OccurredAt: p.OccurredAt,
}
// Fold the new event too: Decide and Apply must agree.
if err := acc.Apply(e); err != nil {
return Result{}, fmt.Errorf("decided event does not fold: %w", err)
}
if _, err := tx.ExecContext(ctx, `INSERT INTO events
(global_position, event_id, stream_id, stream_version, type, schema_version, data, command_id, occurred_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
e.GlobalPosition, e.EventID, e.StreamID, e.StreamVersion, e.Type, e.SchemaVersion,
[]byte(e.Data), cmd.CommandID, e.OccurredAt); err != nil {
return Result{}, err
}
}
last := next + int64(len(pending)) - 1
if err := oneRow(tx.ExecContext(ctx,
`UPDATE feed_allocator SET next_position = $1 WHERE id = 1`, last+1)); err != nil {
return Result{}, err
}
if _, err := tx.ExecContext(ctx, `INSERT INTO command_receipts
(command_id, stream_id, fingerprint, stream_version, last_position) VALUES ($1, $2, $3, $4, $5)`,
cmd.CommandID, cmd.StreamID, fp, newVersion, last); err != nil {
return Result{}, err
}
if err := tx.Commit(); err != nil {
return Result{}, fmt.Errorf("%w: %v", ErrCommitUnknown, err)
}
return Result{StreamVersion: newVersion, LastPosition: last}, nil
}
// Load folds a stream from its latest usable snapshot plus the tail. The
// REPEATABLE READ, read-only transaction makes head, snapshot and tail one view.
func (s *Store) Load(ctx context.Context, streamID string) (Account, error) {
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
if err != nil {
return Account{}, err
}
defer tx.Rollback()
acc, err := load(ctx, tx, streamID)
if err != nil {
return Account{}, err
}
return acc, tx.Commit()
}
func load(ctx context.Context, q querier, streamID string) (Account, error) {
var head int64
err := q.QueryRowContext(ctx, `SELECT version FROM streams WHERE id = $1`, streamID).Scan(&head)
if errors.Is(err, sql.ErrNoRows) {
return NewAccount(streamID), nil
}
if err != nil {
return Account{}, err
}
acc := NewAccount(streamID)
var snapVersion int64
var format int
var state []byte
err = q.QueryRowContext(ctx,
`SELECT version, format, state FROM snapshots WHERE stream_id = $1`, streamID).Scan(&snapVersion, &format, &state)
switch {
case err == nil:
if restored, ok := RestoreSnapshot(streamID, snapVersion, format, state, head); ok {
acc = restored
}
case !errors.Is(err, sql.ErrNoRows):
return Account{}, err
}
rows, err := q.QueryContext(ctx, `SELECT event_id, stream_version, global_position, type,
schema_version, data, command_id, occurred_at, recorded_at
FROM events WHERE stream_id = $1 AND stream_version > $2 ORDER BY stream_version`, streamID, acc.Version)
if err != nil {
return Account{}, err
}
defer rows.Close()
for rows.Next() {
e := Event{StreamID: streamID}
var data []byte // *[]byte makes database/sql copy the driver's buffer
if err := rows.Scan(&e.EventID, &e.StreamVersion, &e.GlobalPosition, &e.Type,
&e.SchemaVersion, &data, &e.CommandID, &e.OccurredAt, &e.RecordedAt); err != nil {
return Account{}, err
}
e.Data = data
up, err := Upcast(e)
if err != nil {
return Account{}, err
}
if err := acc.Apply(up); err != nil {
return Account{}, err
}
}
if err := rows.Err(); err != nil {
return Account{}, err
}
if acc.Version != head {
return Account{}, fmt.Errorf("%w: folded v%d, head v%d", ErrCorruptHistory, acc.Version, head)
}
return acc, nil
}
// RestoreSnapshot trusts a snapshot only if format, identity and version
// agree with the stream; otherwise the caller replays from version 0.
func RestoreSnapshot(streamID string, version int64, format int, state []byte, head int64) (Account, bool) {
if format != SnapshotFormat || version < 1 || version > head {
return Account{}, false
}
var a Account
if err := decodeStrict(state, &a); err != nil || a.ID != streamID || a.Version != version || !a.Opened {
return Account{}, false
}
if a.Withdrawals == nil {
a.Withdrawals = map[string]int64{}
}
return a, true
}
// SaveSnapshot folds COMMITTED history itself (never caller-held state with
// unsaved changes) and only replaces an older snapshot. Under REPEATABLE READ
// a concurrent snapshot writer can make this fail with SQLSTATE 40001;
// the caller may simply skip, because snapshots are an optimization.
func (s *Store) SaveSnapshot(ctx context.Context, streamID string) error {
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
if err != nil {
return err
}
defer tx.Rollback()
acc, err := load(ctx, tx, streamID)
if err != nil || acc.Version == 0 {
return err
}
state, err := json.Marshal(acc)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `INSERT INTO snapshots (stream_id, version, format, state)
VALUES ($1, $2, $3, $4)
ON CONFLICT (stream_id) DO UPDATE
SET version = EXCLUDED.version, format = EXCLUDED.format, state = EXCLUDED.state, taken_at = now()
WHERE snapshots.format < EXCLUDED.format
OR (snapshots.format = EXCLUDED.format AND snapshots.version < EXCLUDED.version)`,
streamID, acc.Version, SnapshotFormat, state); err != nil {
return err
}
return tx.Commit()
}
func oneRow(res sql.Result, err error) error {
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("affected %d rows, want 1", n)
}
return nil
}projectionها، checkpointها، فعالسازی blue/green و queryهای read-your-writes:
package es
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
)
// Projection errors. Each one stops the projector without moving its checkpoint.
var (
ErrFeedGap = errors.New("global feed gap")
ErrProjectionDrift = errors.New("read model does not match the event stream")
ErrNotCaughtUp = errors.New("projection has not reached the required position")
ErrStale = errors.New("read model older than the read-your-writes token")
ErrCheckpointMoved = errors.New("checkpoint moved concurrently")
ErrUnknownReadModel = errors.New("no active projection for read model")
)
// Project applies up to limit events after the checkpoint of one projection
// version (for example "balances_v2"). Read-model rows and checkpoint commit
// together, so a crash replays the batch instead of double-applying it.
func (s *Store) Project(ctx context.Context, projection string, limit int) (int, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
// Insert-if-missing, then lock: two first-time runners do not abort each other.
if _, err := tx.ExecContext(ctx, `INSERT INTO projection_checkpoints (projection, position)
VALUES ($1, 0) ON CONFLICT (projection) DO NOTHING`, projection); err != nil {
return 0, err
}
var pos int64
if err := tx.QueryRowContext(ctx, `SELECT position FROM projection_checkpoints
WHERE projection = $1 FOR UPDATE`, projection).Scan(&pos); err != nil {
return 0, err
}
batch, err := readFeed(ctx, tx, pos, limit) // fully read before the next statement
if err != nil {
return 0, err
}
for _, e := range batch {
if e.GlobalPosition != pos+1 {
return 0, fmt.Errorf("%w: want %d, got %d", ErrFeedGap, pos+1, e.GlobalPosition)
}
up, err := Upcast(e)
if err != nil {
return 0, err // fail closed: deploy a build that understands it, then rerun
}
if err := applyBalance(ctx, tx, projection, up); err != nil {
return 0, err
}
pos = e.GlobalPosition
}
if len(batch) == 0 {
return 0, nil
}
if err := oneRow(tx.ExecContext(ctx, `UPDATE projection_checkpoints SET position = $2, updated_at = now()
WHERE projection = $1`, projection, pos)); err != nil {
return 0, err
}
return len(batch), tx.Commit()
}
// applyBalance checks the per-stream version on every row it touches, so a
// missing, duplicated or reordered event is detected instead of absorbed.
func applyBalance(ctx context.Context, tx *sql.Tx, projection string, e Event) error {
var delta int64
switch e.Type {
case TypeAccountOpened:
var p AccountOpened
if err := json.Unmarshal(e.Data, &p); err != nil {
return err
}
res, err := tx.ExecContext(ctx, `INSERT INTO account_balances
(projection, account_id, currency, balance, stream_version, last_occurred_at)
VALUES ($1, $2, $3, 0, $4, $5) ON CONFLICT DO NOTHING`,
projection, e.StreamID, p.Currency, e.StreamVersion, e.OccurredAt)
if err := oneRow(res, err); err != nil {
return fmt.Errorf("%w: open %s: %v", ErrProjectionDrift, e.StreamID, err)
}
return nil
case TypeMoneyDeposited:
var p MoneyDeposited
if err := json.Unmarshal(e.Data, &p); err != nil {
return err
}
delta = p.Amount
case TypeMoneyWithdrawn:
var p MoneyWithdrawn
if err := json.Unmarshal(e.Data, &p); err != nil {
return err
}
delta = -p.Amount
case TypeWithdrawalReversed:
var p WithdrawalReversed
if err := json.Unmarshal(e.Data, &p); err != nil {
return err
}
delta = p.Amount
default:
return fmt.Errorf("%w: %s", ErrUnknownEvent, e.Type)
}
res, err := tx.ExecContext(ctx, `UPDATE account_balances
SET balance = balance + $3, stream_version = $4, last_occurred_at = $5
WHERE projection = $1 AND account_id = $2 AND stream_version = $4 - 1`,
projection, e.StreamID, delta, e.StreamVersion, e.OccurredAt)
if err := oneRow(res, err); err != nil {
return fmt.Errorf("%w: %s v%d: %v", ErrProjectionDrift, e.StreamID, e.StreamVersion, err)
}
return nil
}
// Head is the last committed global position.
func (s *Store) Head(ctx context.Context) (int64, error) {
var next int64
err := s.db.QueryRowContext(ctx, `SELECT next_position FROM feed_allocator WHERE id = 1`).Scan(&next)
return next - 1, err
}
// ActivateProjection points readers of readModel at a projection version
// once it has caught up to minPosition (normally Head at cut-over time).
// The old version keeps running until nobody reads it, then is dropped.
func (s *Store) ActivateProjection(ctx context.Context, readModel, projection string, minPosition int64) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var pos int64
if err := tx.QueryRowContext(ctx, `SELECT position FROM projection_checkpoints
WHERE projection = $1 FOR SHARE`, projection).Scan(&pos); err != nil {
return err
}
if pos < minPosition {
return fmt.Errorf("%w: %s at %d, need %d", ErrNotCaughtUp, projection, pos, minPosition)
}
if _, err := tx.ExecContext(ctx, `INSERT INTO active_projections (read_model, projection) VALUES ($1, $2)
ON CONFLICT (read_model) DO UPDATE SET projection = EXCLUDED.projection`, readModel, projection); err != nil {
return err
}
return tx.Commit()
}
// Balance is a query-side answer with the position it reflects.
type Balance struct {
AccountID string
Currency string
Balance int64
AsOf int64 // checkpoint of the projection that answered
}
// QueryBalance reads the active projection. If its checkpoint is older than
// atLeast (the LastPosition a client got from Execute), it returns ErrStale so
// the caller can wait, retry, or read the write model instead.
func (s *Store) QueryBalance(ctx context.Context, accountID string, atLeast int64) (Balance, error) {
var b Balance
err := s.db.QueryRowContext(ctx, `SELECT c.position, b.account_id, b.currency, b.balance
FROM active_projections a
JOIN projection_checkpoints c ON c.projection = a.projection
LEFT JOIN account_balances b ON b.projection = a.projection AND b.account_id = $1
WHERE a.read_model = 'balances'`, accountID).Scan(&b.AsOf, nullString{&b.AccountID}, nullString{&b.Currency}, nullInt{&b.Balance})
if errors.Is(err, sql.ErrNoRows) {
return Balance{}, ErrUnknownReadModel
}
if err != nil {
return Balance{}, err
}
if b.AsOf < atLeast {
return Balance{}, fmt.Errorf("%w: at %d, token %d", ErrStale, b.AsOf, atLeast)
}
if b.AccountID == "" {
return Balance{}, sql.ErrNoRows
}
return b, nil
}
// WaitForPosition polls until a projection reaches token or ctx ends.
func (s *Store) WaitForPosition(ctx context.Context, projection string, token int64, every time.Duration) error {
t := time.NewTicker(every)
defer t.Stop()
for {
var pos int64
err := s.db.QueryRowContext(ctx, `SELECT position FROM projection_checkpoints
WHERE projection = $1`, projection).Scan(&pos)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if pos >= token {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
}
}
}
// Checkpoint returns a consumer's position, creating it at 0 if missing.
func (s *Store) Checkpoint(ctx context.Context, name string) (int64, error) {
var pos int64
err := s.db.QueryRowContext(ctx, `INSERT INTO projection_checkpoints (projection, position) VALUES ($1, 0)
ON CONFLICT (projection) DO UPDATE SET projection = EXCLUDED.projection
RETURNING position`, name).Scan(&pos)
return pos, err
}
// AdvanceCheckpoint moves a relay checkpoint from -> to, or fails if another
// relay instance moved it first.
func (s *Store) AdvanceCheckpoint(ctx context.Context, name string, from, to int64) error {
err := oneRow(s.db.ExecContext(ctx, `UPDATE projection_checkpoints SET position = $3, updated_at = now()
WHERE projection = $1 AND position = $2`, name, from, to))
if err != nil {
return fmt.Errorf("%w: %s: %v", ErrCheckpointMoved, name, err)
}
return nil
}
// ReadFeed returns committed events after a global position, in order.
func (s *Store) ReadFeed(ctx context.Context, after int64, limit int) ([]Event, error) {
return readFeed(ctx, s.db, after, limit)
}
func readFeed(ctx context.Context, q querier, after int64, limit int) ([]Event, error) {
rows, err := q.QueryContext(ctx, `SELECT event_id, stream_id, stream_version, global_position, type,
schema_version, data, command_id, occurred_at, recorded_at
FROM events WHERE global_position > $1 ORDER BY global_position LIMIT $2`, after, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Event
for rows.Next() {
var e Event
var data []byte
if err := rows.Scan(&e.EventID, &e.StreamID, &e.StreamVersion, &e.GlobalPosition, &e.Type,
&e.SchemaVersion, &data, &e.CommandID, &e.OccurredAt, &e.RecordedAt); err != nil {
return nil, err
}
e.Data = data
out = append(out, e)
}
return out, rows.Err()
}
type nullString struct{ dst *string }
func (n nullString) Scan(v any) error {
var s sql.NullString
if err := s.Scan(v); err != nil {
return err
}
*n.dst = s.String
return nil
}
type nullInt struct{ dst *int64 }
func (n nullInt) Scan(v any) error {
var i sql.NullInt64
if err := i.Scan(v); err != nil {
return err
}
*n.dst = i.Int64
return nil
}ابزارهای crypto-shredding:
package es
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"database/sql"
"errors"
"fmt"
)
// ErrShredded means the subject's key is gone: the sealed value is
// permanently unreadable, while the event row itself stays in place.
var ErrShredded = errors.New("subject key deleted")
// SubjectKey returns the subject's 256-bit data key, creating it once.
// Production systems usually wrap this key with a KMS key instead of storing
// it in plain bytea next to the data.
func (s *Store) SubjectKey(ctx context.Context, subjectID string) ([]byte, error) {
fresh := make([]byte, 32)
if _, err := rand.Read(fresh); err != nil {
return nil, err
}
if _, err := s.db.ExecContext(ctx, `INSERT INTO subject_keys (subject_id, data_key) VALUES ($1, $2)
ON CONFLICT (subject_id) DO NOTHING`, subjectID, fresh); err != nil {
return nil, err
}
return s.existingKey(ctx, subjectID)
}
func (s *Store) existingKey(ctx context.Context, subjectID string) ([]byte, error) {
var key []byte
err := s.db.QueryRowContext(ctx, `SELECT data_key FROM subject_keys WHERE subject_id = $1`, subjectID).Scan(&key)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrShredded
}
return key, err
}
// ForgetSubject deletes the key. Copies in backups, replicas, logs, caches,
// read models and broker topics are NOT affected by this statement.
func (s *Store) ForgetSubject(ctx context.Context, subjectID string) error {
_, err := s.db.ExecContext(ctx, `DELETE FROM subject_keys WHERE subject_id = $1`, subjectID)
return err
}
// RevealOwnerName decrypts the sealed field of an AccountOpened payload.
func (s *Store) RevealOwnerName(ctx context.Context, p AccountOpened) (string, error) {
key, err := s.existingKey(ctx, p.SubjectID)
if err != nil {
return "", err
}
plain, err := Open(key, p.SubjectID, p.OwnerNameSealed)
return string(plain), err
}
// Seal encrypts with AES-256-GCM; the subject ID is bound as associated data
// so a sealed value cannot be moved to another subject.
func Seal(key []byte, subjectID string, plaintext []byte) ([]byte, error) {
gcm, err := newGCM(key)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, []byte(subjectID)), nil
}
// Open reverses Seal.
func Open(key []byte, subjectID string, sealed []byte) ([]byte, error) {
gcm, err := newGCM(key)
if err != nil {
return nil, err
}
if len(sealed) < gcm.NonceSize() {
return nil, errors.New("sealed value too short")
}
nonce, body := sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():]
return gcm.Open(nil, nonce, body, []byte(subjectID))
}
func newGCM(key []byte) (cipher.AEAD, error) {
if len(key) != 32 {
return nil, fmt.Errorf("want 32-byte key, got %d", len(key))
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCM(block)
}نگاه Go
این کتابخانه فقط از database/sql، encoding/json، crypto/* و context استفاده میکند؛ برنامهٔ میزبان یک *sql.DB با درایور PostgreSQL (مثلاً آداپتور stdlib در pgx) باز میکند و اسکیما را اعمال میکند. BeginTx با sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true} دید سازگار بارگذاری را میدهد؛ defer tx.Rollback() پس از Commit بیضرر است (sql.ErrTxDone). ردیفها پیش از دستور بعدی در تراکنش کامل خوانده میشوند، چون برخی درایورها وقتی یک result set روی همان اتصال باز است نمیتوانند دستور دیگری اجرا کنند. jsonb در []byte خوانده میشود که database/sql کپیاش میکند، نه در json.RawMessage که به حافظهٔ درایور اشاره میماند. آزمونها (go test ./...) قواعد ثابت، upcasting، fingerprint، اعتبارسنجی snapshot، مُهرکردن و ترتیب relay را بدون پایگاه داده پوشش میدهند؛ رفتار خود SQL در آزمایشگاه بررسی میشود.
package es
import (
"bytes"
"context"
"encoding/json"
"errors"
"math"
"testing"
"time"
)
var t0 = time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)
// fold runs Decide and Apply the way Execute does, without a database.
func fold(t *testing.T, a *Account, c Command) error {
t.Helper()
c.StreamID, c.OccurredAt = a.ID, t0
if c.CommandID == "" {
c.CommandID = "cmd-" + c.Kind
}
pending, err := Decide(*a, c)
if err != nil {
return err
}
for i, p := range pending {
e := Event{EventID: c.CommandID, StreamID: a.ID, StreamVersion: a.Version + 1 + int64(i),
Type: p.Type, SchemaVersion: currentSchema[p.Type], Data: p.Data, OccurredAt: p.OccurredAt}
if err := a.Apply(e); err != nil {
t.Fatalf("decided event does not fold: %v", err)
}
}
return nil
}
func opened(t *testing.T) Account {
a := NewAccount("acc-1")
if err := fold(t, &a, Command{Kind: KindOpen, Currency: "EUR", SubjectID: "sub-1"}); err != nil {
t.Fatal(err)
}
return a
}
func TestDecideRejectsInvalidMoney(t *testing.T) {
a := opened(t)
for _, amt := range []int64{0, -1, math.MinInt64} {
if err := fold(t, &a, Command{Kind: KindDeposit, Amount: amt}); !errors.Is(err, ErrInvalidAmount) {
t.Errorf("deposit %d: got %v", amt, err)
}
if err := fold(t, &a, Command{Kind: KindWithdraw, Amount: amt}); !errors.Is(err, ErrInvalidAmount) {
t.Errorf("withdraw %d: got %v", amt, err)
}
}
if err := fold(t, &a, Command{Kind: KindDeposit, Amount: math.MaxInt64}); err != nil {
t.Fatal(err)
}
if err := fold(t, &a, Command{Kind: KindDeposit, Amount: 1}); !errors.Is(err, ErrOverflow) {
t.Errorf("overflow: got %v", err)
}
}
func TestStateGuards(t *testing.T) {
a := NewAccount("acc-1")
if err := fold(t, &a, Command{Kind: KindDeposit, Amount: 5}); !errors.Is(err, ErrNotOpen) {
t.Errorf("deposit before open: %v", err)
}
if err := fold(t, &a, Command{Kind: KindOpen, Currency: "eur", SubjectID: "s"}); !errors.Is(err, ErrInvalidCommand) {
t.Errorf("bad currency: %v", err)
}
a = opened(t)
if err := fold(t, &a, Command{Kind: KindOpen, Currency: "EUR", SubjectID: "s"}); !errors.Is(err, ErrAlreadyOpen) {
t.Errorf("open twice: %v", err)
}
if err := fold(t, &a, Command{Kind: KindWithdraw, Amount: 1}); !errors.Is(err, ErrInsufficientFunds) {
t.Errorf("overdraft: %v", err)
}
}
func TestCompensatingReversalOnlyOnce(t *testing.T) {
a := opened(t)
_ = fold(t, &a, Command{Kind: KindDeposit, Amount: 100})
if err := fold(t, &a, Command{CommandID: "w1", Kind: KindWithdraw, Amount: 30, Reason: "atm"}); err != nil {
t.Fatal(err)
}
rev := Command{CommandID: "r1", Kind: KindReverse, Amount: 30, TargetEventID: "w1", Reason: "duplicate charge"}
if err := fold(t, &a, rev); err != nil {
t.Fatal(err)
}
if a.Balance != 100 || a.Version != 4 {
t.Fatalf("balance %d version %d", a.Balance, a.Version)
}
rev.CommandID = "r2"
if err := fold(t, &a, rev); !errors.Is(err, ErrUnknownWithdrawal) {
t.Errorf("second reversal: %v", err)
}
}
func TestApplyRejectsGapsAndForeignStreams(t *testing.T) {
a := opened(t)
dep := json.RawMessage(`{"amount":5}`)
if err := a.Apply(Event{StreamID: "acc-1", StreamVersion: 3, Type: TypeMoneyDeposited, Data: dep}); !errors.Is(err, ErrCorruptHistory) {
t.Errorf("gap: %v", err)
}
if err := a.Apply(Event{StreamID: "acc-2", StreamVersion: 2, Type: TypeMoneyDeposited, Data: dep}); !errors.Is(err, ErrCorruptHistory) {
t.Errorf("foreign stream: %v", err)
}
if err := a.Apply(Event{StreamID: "acc-1", StreamVersion: 2, Type: TypeMoneyWithdrawn, Data: json.RawMessage(`{"amount":5,"reason":""}`)}); !errors.Is(err, ErrCorruptHistory) {
t.Errorf("history overdraft: %v", err)
}
}
func TestUpcastWithdrawalV1(t *testing.T) {
old := Event{EventID: "e1", Type: TypeMoneyWithdrawn, SchemaVersion: 1, Data: json.RawMessage(`{"amount_cents":1250}`)}
up, err := Upcast(old)
if err != nil {
t.Fatal(err)
}
var p MoneyWithdrawn
if err := decodeStrict(up.Data, &p); err != nil || up.SchemaVersion != 2 || p.Amount != 1250 {
t.Fatalf("got %+v %+v %v", up, p, err)
}
if !bytes.Equal(old.Data, []byte(`{"amount_cents":1250}`)) {
t.Fatal("upcast must not mutate the stored payload")
}
}
func TestUpcastFailsClosed(t *testing.T) {
cases := []Event{
{Type: "AccountFrozen", SchemaVersion: 1},
{Type: TypeMoneyWithdrawn, SchemaVersion: 3},
{Type: TypeMoneyDeposited, SchemaVersion: 2},
}
for _, e := range cases {
if _, err := Upcast(e); !errors.Is(err, ErrUnknownEvent) {
t.Errorf("%s v%d: %v", e.Type, e.SchemaVersion, err)
}
}
if _, err := Upcast(Event{Type: TypeMoneyWithdrawn, SchemaVersion: 1, Data: json.RawMessage(`{"amount_cents":1,"extra":1}`)}); err == nil {
t.Error("unknown field accepted")
}
}
func TestFingerprint(t *testing.T) {
c := Command{CommandID: "c1", StreamID: "acc-1", Kind: KindWithdraw, Amount: 10, ExpectedVersion: 4, OccurredAt: t0}
retry := c
retry.CommandID = "c1-retry-id-is-not-hashed"
other := c
other.Amount = 11
f1, _ := c.Fingerprint()
f2, _ := retry.Fingerprint()
f3, _ := other.Fingerprint()
if f1 != f2 || f1 == f3 {
t.Fatalf("fingerprints %s %s %s", f1, f2, f3)
}
}
func TestRestoreSnapshotValidates(t *testing.T) {
a := opened(t)
state, _ := json.Marshal(a)
if _, ok := RestoreSnapshot("acc-1", 1, SnapshotFormat, state, 1); !ok {
t.Fatal("valid snapshot rejected")
}
bad := []struct {
id string
version int64
format int
head int64
}{
{"acc-2", 1, SnapshotFormat, 1}, // other stream
{"acc-1", 1, SnapshotFormat + 1, 1}, // unknown format
{"acc-1", 2, SnapshotFormat, 1}, // ahead of committed head
}
for _, b := range bad {
if _, ok := RestoreSnapshot(b.id, b.version, b.format, state, b.head); ok {
t.Errorf("accepted %+v", b)
}
}
}
func TestSealOpenAndShred(t *testing.T) {
key := bytes.Repeat([]byte{7}, 32)
sealed, err := Seal(key, "sub-1", []byte("Ada Example"))
if err != nil {
t.Fatal(err)
}
if plain, err := Open(key, "sub-1", sealed); err != nil || string(plain) != "Ada Example" {
t.Fatalf("open: %q %v", plain, err)
}
if _, err := Open(key, "sub-2", sealed); err == nil {
t.Error("sealed value moved to another subject")
}
if _, err := Open(bytes.Repeat([]byte{8}, 32), "sub-1", sealed); err == nil {
t.Error("wrong key accepted")
}
}
type fakeFeed struct {
pos int64
events []Event
}
func (f *fakeFeed) Checkpoint(context.Context, string) (int64, error) { return f.pos, nil }
func (f *fakeFeed) ReadFeed(_ context.Context, after int64, limit int) ([]Event, error) {
var out []Event
for _, e := range f.events {
if e.GlobalPosition > after && len(out) < limit {
out = append(out, e)
}
}
return out, nil
}
func (f *fakeFeed) AdvanceCheckpoint(_ context.Context, _ string, from, to int64) error {
if f.pos != from {
return ErrCheckpointMoved
}
f.pos = to
return nil
}
func TestRelayStopsAtFirstFailure(t *testing.T) {
f := &fakeFeed{events: []Event{{GlobalPosition: 1}, {GlobalPosition: 2}, {GlobalPosition: 3}}}
boom := errors.New("broker unavailable")
n, err := RelayOnce(context.Background(), f, "relay:test", 10, func(_ context.Context, e Event) error {
if e.GlobalPosition == 3 {
return boom
}
return nil
})
if !errors.Is(err, boom) || n != 2 || f.pos != 2 {
t.Fatalf("n=%d pos=%d err=%v", n, f.pos, err)
}
}
func TestRelayRefusesFeedGap(t *testing.T) {
f := &fakeFeed{events: []Event{{GlobalPosition: 1}, {GlobalPosition: 3}}}
n, err := RelayOnce(context.Background(), f, "relay:test", 10, func(context.Context, Event) error { return nil })
if !errors.Is(err, ErrFeedGap) || n != 1 || f.pos != 1 {
t.Fatalf("n=%d pos=%d err=%v", n, f.pos, err)
}
}Laravel
Before
همان بهروزرسانی موجودی با Query Builder: برای CRUD درست، بدون تاریخچه.
<?php
namespace App\Accounts\Before;
use DomainException;
use Illuminate\Support\Facades\DB;
final class AccountBalanceService
{
// Correct for a CRUD system: atomic, no overdraft. But only the latest
// number survives; why and when it changed is lost unless an audit table
// is written separately (and can then disagree with this row).
public function withdraw(string $accountId, int $amount): void
{
if ($amount <= 0) {
throw new DomainException('Amount must be positive.');
}
$updated = DB::table('accounts')
->where('id', $accountId)
->where('balance', '>=', $amount)
->decrement('balance', $amount);
if ($updated !== 1) {
throw new DomainException('Insufficient funds.');
}
}
}After
aggregate با upcasting، fold و تصمیم، در فایل PSR-4 مخصوص خودش:
<?php
namespace App\Accounts;
use DomainException;
use InvalidArgumentException;
use UnexpectedValueException;
/**
* Write-side state folded from one stream. Amounts are integer minor units of
* the account currency; PHP int is 64-bit on the supported platforms.
*/
final class Account
{
public bool $opened = false;
public string $currency = '';
public int $balance = 0;
public int $version = 0;
/** @var array<string, int> reversible withdrawals by event id */
public array $withdrawals = [];
public function __construct(public readonly string $id) {}
/** Converts a stored payload to the current schema; unknown versions fail closed. */
public static function upcast(string $type, int $schemaVersion, array $data): array
{
return match (true) {
$type === 'MoneyWithdrawn' && $schemaVersion === 1 => [
'amount' => self::positive($data['amount_cents'] ?? null),
'reason' => 'unspecified (v1)',
],
$type === 'MoneyWithdrawn' && $schemaVersion === 2,
in_array($type, ['AccountOpened', 'MoneyDeposited', 'WithdrawalReversed'], true) && $schemaVersion === 1 => $data,
default => throw new UnexpectedValueException("Unknown event {$type} v{$schemaVersion}."),
};
}
/** Folds one upcast event; deterministic, no I/O. Throws on inconsistent history. */
public function apply(string $eventId, int $streamVersion, string $type, array $data): void
{
if ($streamVersion !== $this->version + 1 || ($type === 'AccountOpened') === $this->opened) {
throw new UnexpectedValueException("Corrupt history at {$this->id} v{$streamVersion}.");
}
switch ($type) {
case 'AccountOpened':
$this->opened = true;
$this->currency = (string) $data['currency'];
break;
case 'MoneyDeposited':
$this->credit(self::positive($data['amount'] ?? null));
break;
case 'MoneyWithdrawn':
$amount = self::positive($data['amount'] ?? null);
if ($amount > $this->balance) {
throw new UnexpectedValueException("Overdraft in history at {$this->id} v{$streamVersion}.");
}
$this->balance -= $amount;
$this->withdrawals[$eventId] = $amount;
break;
case 'WithdrawalReversed':
$target = (string) $data['withdrawal_event_id'];
$amount = self::positive($data['amount'] ?? null);
if (($this->withdrawals[$target] ?? null) !== $amount) {
throw new UnexpectedValueException("Reversal of unknown withdrawal {$target}.");
}
$this->credit($amount);
unset($this->withdrawals[$target]);
break;
default:
throw new UnexpectedValueException("Unknown event {$type}.");
}
$this->version = $streamVersion;
}
/**
* Pure decision: the event to append, or a DomainException.
*
* @return array{type: string, data: array<string, mixed>}
*/
public function decide(array $command): array
{
$kind = $command['kind'] ?? '';
if ($kind === 'open') {
if ($this->opened) {
throw new DomainException('Account already open.');
}
if (! preg_match('/^[A-Z]{3}$/', (string) ($command['currency'] ?? '')) || empty($command['subject_id'])) {
throw new InvalidArgumentException('Currency and subject are required.');
}
return ['type' => 'AccountOpened', 'data' => [
'currency' => $command['currency'],
'subject_id' => $command['subject_id'],
]];
}
if (! $this->opened) {
throw new DomainException('Account not open.');
}
$amount = $command['amount'] ?? null;
if (! is_int($amount) || $amount <= 0) {
throw new InvalidArgumentException('Amount must be a positive integer.');
}
return match ($kind) {
'deposit' => $this->guardCredit($amount, ['type' => 'MoneyDeposited', 'data' => ['amount' => $amount]]),
'withdraw' => $amount > $this->balance
? throw new DomainException('Insufficient funds.')
: ['type' => 'MoneyWithdrawn', 'data' => ['amount' => $amount, 'reason' => (string) ($command['reason'] ?? '')]],
'reverse' => ($this->withdrawals[$command['target_event_id'] ?? ''] ?? null) !== $amount
? throw new DomainException('Withdrawal unknown or already reversed.')
: $this->guardCredit($amount, ['type' => 'WithdrawalReversed', 'data' => [
'withdrawal_event_id' => $command['target_event_id'],
'amount' => $amount,
'reason' => (string) ($command['reason'] ?? ''),
]]),
default => throw new InvalidArgumentException("Unknown command {$kind}."),
};
}
private function guardCredit(int $amount, array $event): array
{
if ($this->balance > PHP_INT_MAX - $amount) {
throw new DomainException('Balance would overflow.');
}
return $event;
}
private function credit(int $amount): void
{
$this->guardCredit($amount, []);
$this->balance += $amount;
}
private static function positive(mixed $value): int
{
if (! is_int($value) || $value <= 0) {
throw new UnexpectedValueException('Stored amount must be a positive integer.');
}
return $value;
}
}event store روی یک اتصال صریح، با معنای DB::transaction از طریق متد transaction() همان اتصال، lockForUpdate()، insertOrIgnore() و شمارش ردیفهای تغییرکرده:
<?php
namespace App\EventSourcing;
use App\Accounts\Account;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use UnexpectedValueException;
final class EventStore
{
public const ANY_VERSION = -1;
private ConnectionInterface $db;
public function __construct(DatabaseManager $databases)
{
// One explicit connection for the lock, the reads, the writes and COMMIT.
$this->db = $databases->connection('pgsql');
}
/**
* Decide and append one event atomically; retries with the same command ID
* and the same intent return the stored result instead of appending again.
*
* @return array{stream_version: int, last_position: int, duplicate: bool}
*/
public function execute(string $commandId, string $streamId, int $expectedVersion, array $command): array
{
$fingerprint = hash('sha256', json_encode([$streamId, $expectedVersion, $command], JSON_THROW_ON_ERROR));
return $this->db->transaction(function () use ($commandId, $streamId, $expectedVersion, $command, $fingerprint): array {
// Held until COMMIT: positions become visible in order, without gaps.
$next = (int) $this->db->table('feed_allocator')->where('id', 1)->lockForUpdate()->value('next_position');
$receipt = $this->db->table('command_receipts')->where('command_id', $commandId)->first();
if ($receipt !== null) {
if (! hash_equals($receipt->fingerprint, $fingerprint)) {
throw new CommandIdReused($commandId);
}
return [
'stream_version' => (int) $receipt->stream_version,
'last_position' => (int) $receipt->last_position,
'duplicate' => true,
];
}
$account = $this->fold($streamId);
if ($expectedVersion !== self::ANY_VERSION && $account->version !== $expectedVersion) {
throw new WrongExpectedVersion($streamId, $expectedVersion, $account->version);
}
$event = $account->decide($command);
$eventId = $commandId.'/0';
$version = $account->version + 1;
$account->apply($eventId, $version, $event['type'], $event['data']);
$moved = $version === 1
? $this->db->table('streams')->insertOrIgnore(['id' => $streamId, 'version' => 1])
: $this->db->table('streams')->where('id', $streamId)->where('version', $version - 1)->update(['version' => $version]);
if ($moved !== 1) {
throw new WrongExpectedVersion($streamId, $version - 1, -1);
}
$this->db->table('events')->insert([
'global_position' => $next,
'event_id' => $eventId,
'stream_id' => $streamId,
'stream_version' => $version,
'type' => $event['type'],
'schema_version' => $event['type'] === 'MoneyWithdrawn' ? 2 : 1,
'data' => json_encode($event['data'], JSON_THROW_ON_ERROR),
'command_id' => $commandId,
'occurred_at' => $command['occurred_at'],
]);
$this->db->table('feed_allocator')->where('id', 1)->update(['next_position' => $next + 1]);
$this->db->table('command_receipts')->insert([
'command_id' => $commandId,
'stream_id' => $streamId,
'fingerprint' => $fingerprint,
'stream_version' => $version,
'last_position' => $next,
]);
return ['stream_version' => $version, 'last_position' => $next, 'duplicate' => false];
}, 1);
}
/** Folds the stream inside one REPEATABLE READ, read-only snapshot. */
public function load(string $streamId): Account
{
return $this->db->transaction(function () use ($streamId): Account {
$this->db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return $this->fold($streamId);
});
}
private function fold(string $streamId): Account
{
$account = new Account($streamId);
$head = (int) ($this->db->table('streams')->where('id', $streamId)->value('version') ?? 0);
$rows = $this->db->table('events')
->where('stream_id', $streamId)
->orderBy('stream_version')
->get(['event_id', 'stream_version', 'type', 'schema_version', 'data']);
foreach ($rows as $row) {
$data = Account::upcast($row->type, (int) $row->schema_version, json_decode($row->data, true, 512, JSON_THROW_ON_ERROR));
$account->apply($row->event_id, (int) $row->stream_version, $row->type, $data);
}
if ($account->version !== $head) {
throw new UnexpectedValueException("Folded v{$account->version}, head v{$head} for {$streamId}.");
}
return $account;
}
}<?php
namespace App\EventSourcing;
use RuntimeException;
final class WrongExpectedVersion extends RuntimeException
{
public function __construct(string $streamId, int $expected, int $actual)
{
parent::__construct("Stream {$streamId} is at version {$actual}, expected {$expected}.");
}
}<?php
namespace App\EventSourcing;
use RuntimeException;
final class CommandIdReused extends RuntimeException
{
public function __construct(string $commandId)
{
parent::__construct("Command ID {$commandId} was already used for a different intent.");
}
}projector با checkpoint و بررسی نسخه در همان تراکنش:
<?php
namespace App\Accounts;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use UnexpectedValueException;
/**
* Projects the global feed into account_balances for one projection version
* (balances_v1, balances_v2 ...). Rows and checkpoint commit together.
*/
final class BalanceProjector
{
private ConnectionInterface $db;
public function __construct(DatabaseManager $databases)
{
$this->db = $databases->connection('pgsql');
}
public function project(string $projection, int $limit = 500): int
{
return $this->db->transaction(function () use ($projection, $limit): int {
$this->db->table('projection_checkpoints')->insertOrIgnore(['projection' => $projection, 'position' => 0]);
$position = (int) $this->db->table('projection_checkpoints')
->where('projection', $projection)->lockForUpdate()->value('position');
$events = $this->db->table('events')
->where('global_position', '>', $position)
->orderBy('global_position')
->limit($limit)
->get();
foreach ($events as $event) {
if ((int) $event->global_position !== $position + 1) {
throw new UnexpectedValueException("Feed gap after {$position}.");
}
$data = Account::upcast($event->type, (int) $event->schema_version, json_decode($event->data, true, 512, JSON_THROW_ON_ERROR));
$this->apply($projection, $event, $data);
$position = (int) $event->global_position;
}
if ($events->isNotEmpty()) {
$this->db->table('projection_checkpoints')
->where('projection', $projection)
->update(['position' => $position, 'updated_at' => now()]);
}
return $events->count();
}, 1);
}
private function apply(string $projection, object $event, array $data): void
{
$version = (int) $event->stream_version;
if ($event->type === 'AccountOpened') {
$inserted = $this->db->table('account_balances')->insertOrIgnore([
'projection' => $projection,
'account_id' => $event->stream_id,
'currency' => $data['currency'],
'balance' => 0,
'stream_version' => $version,
'last_occurred_at' => $event->occurred_at,
]);
if ($inserted !== 1) {
throw new UnexpectedValueException("Account {$event->stream_id} already projected.");
}
return;
}
$delta = match ($event->type) {
'MoneyDeposited', 'WithdrawalReversed' => $data['amount'],
'MoneyWithdrawn' => -$data['amount'],
};
$updated = $this->db->table('account_balances')
->where('projection', $projection)
->where('account_id', $event->stream_id)
->where('stream_version', $version - 1)
->update([
'balance' => $this->db->raw('balance + '.(int) $delta),
'stream_version' => $version,
'last_occurred_at' => $event->occurred_at,
]);
if ($updated !== 1) {
throw new UnexpectedValueException("Projection drift at {$event->stream_id} v{$version}.");
}
}
}نگاه Laravel
DB::transaction در Laravel 13 با exception عقبگرد میکند و exception را دوباره پرتاب میکند و برای deadlock تعداد تلاش میپذیرد؛ store عدد 1 میدهد تا تکرار تصمیم فراخواننده باشد (با همان command ID). lockForUpdate() عبارت FOR UPDATE میسازد؛ insertOrIgnore() و update() تعداد ردیفهای تغییرکرده را برمیگردانند و store آن را بررسی میکند. همهٔ دستورها از اتصالی میگذرند که یک بار در سازنده گرفته شده، پس قفل، خواندن، نوشتن و COMMIT روی یک اتصال PDO هستند؛ مخلوطکردن DB::table() روی اتصال پیشفرض با اتصالی دیگر تراکنش را بیصدا دو تکه میکند. SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY اولین دستور تراکنش load() است، که PostgreSQL لازم دارد.
بستهٔ spatie/laravel-event-sourcing (مستندات v7 برای این فصل خوانده شد) aggregate root (retrieve($uuid)، recordThat()، persist())، projector و reactor، snapshotی که ویژگیهای public یک aggregate را ذخیره میکند و فرمان php artisan event-sourcing:replay را فراهم میکند. مستند آن محدودیتهایی را میگوید که باید دانست: reactorها هنگام replay هرگز فراخوانده نمیشوند؛ گزینهٔ --from تابع resetState را صدا نمیزند و بسته پیگیری نمیکند هر projector کدام رویدادها را قبلاً پردازش کرده؛ صفی را توصیه میکند که هر بار یک job پردازش کند تا projectorها رویدادها را به ترتیب بگیرند؛ replay با timestampهای مدل، زمانِ replay را ثبت میکند مگر اینکه زمان رویداد را کپی کنید. persist کردن aggregate رویدادهای جدید را به projectorها و reactorها میدهد، اما reactorی که به broker میفرستد همچنان dual write است: برای انتشار مطمئن از outbox استفاده کنید. رفتار همروندی آن را با نسخهای که نصب میکنید بررسی کنید.
تفاوتهای اجرا در brokerها
در همهٔ گونههای زیر، پایگاه داده event store است. brokerها کپیهایی از feed commitشده را از طریق حلقهٔ عمومی RelayOnce به سرویسهای دیگر میبرند:
package es
import (
"context"
"fmt"
)
// Feed is the part of Store a broker relay needs; tests use a fake.
type Feed interface {
Checkpoint(ctx context.Context, name string) (int64, error)
ReadFeed(ctx context.Context, after int64, limit int) ([]Event, error)
AdvanceCheckpoint(ctx context.Context, name string, from, to int64) error
}
// PublishFunc must return nil only after the broker durably accepted e.
type PublishFunc func(ctx context.Context, e Event) error
// RelayOnce copies the next batch of the committed feed to a broker. It is at
// least once: a crash after publish and before AdvanceCheckpoint republishes,
// so consumers deduplicate by EventID or by (StreamID, StreamVersion).
func RelayOnce(ctx context.Context, feed Feed, name string, limit int, publish PublishFunc) (int, error) {
from, err := feed.Checkpoint(ctx, name)
if err != nil {
return 0, err
}
batch, err := feed.ReadFeed(ctx, from, limit)
if err != nil {
return 0, err
}
done := from
var pubErr error
for _, e := range batch {
if e.GlobalPosition != done+1 {
pubErr = fmt.Errorf("%w: want %d, got %d", ErrFeedGap, done+1, e.GlobalPosition)
break
}
if pubErr = publish(ctx, e); pubErr != nil {
break
}
done = e.GlobalPosition
}
if done > from {
if err := feed.AdvanceCheckpoint(ctx, name, from, done); err != nil {
return 0, err
}
}
return int(done - from), pubErr
}RabbitMQ
صفهای classic و quorum مخرباند: پیامی که مصرف و تأیید شد از بین میرود، پس صف نمیتواند تاریخچه را برای مشترک جدید replay کند. RabbitMQ Streams (x-queue-type: stream) لاگی append-only با خواندن غیرمخرب است؛ consumerها با x-stream-offset (first، last، next، یک عدد یا یک timestamp) به offset میچسبند، prefetch مخصوص هر consumer لازم دارند و retention (x-max-age، x-max-length-bytes) segmentهای قدیمی را بهطور کامل دور میریزد. streamها در کلاینتهایی که پشتیبانی میکنند deduplication سمت ناشر بر اساس نام producer و publishing ID هم دارند. هیچکدام نسخهٔ stream را بررسی نمیکند.
انتشار باید با publisher confirms و mandatory=true باشد: RabbitMQ پیام غیرقابلمسیریابی را هم confirm میکند و فقط انتشار mandatory یک basic.return تولید میکند که broker آن را پیش از basic.ack میفرستد. ناشر زیر return را شکست حساب میکند تا نبودِ یک binding نتواند checkpoint relay را جلو ببرد.
// Package rabbitrelay publishes the committed event feed to RabbitMQ.
// PostgreSQL remains the event store; RabbitMQ is transport. A RabbitMQ
// stream adds a replayable, retention-bounded copy for subscribers.
package rabbitrelay
import (
"context"
"errors"
"fmt"
amqp "github.com/rabbitmq/amqp091-go"
"academy/event-sourcing-cqrs/es"
)
var (
ErrNacked = errors.New("broker nacked the publish")
ErrUnroutable = errors.New("message returned as unroutable")
)
// DeclareStream declares a durable RabbitMQ stream (not a classic or quorum
// queue): reading does not remove messages. Retention discards whole old
// segments, so rebuilds read PostgreSQL, never this stream.
func DeclareStream(ch *amqp.Channel, name, maxAge string) error {
_, err := ch.QueueDeclare(name, true, false, false, false, amqp.Table{
"x-queue-type": "stream",
"x-max-age": maxAge, // for example "7D"
})
return err
}
// Publisher sends one message at a time with publisher confirms and
// mandatory=true, so "unroutable" cannot masquerade as "confirmed".
type Publisher struct {
ch *amqp.Channel
returns chan amqp.Return
exchange string
}
func NewPublisher(ch *amqp.Channel, exchange string) (*Publisher, error) {
if err := ch.Confirm(false); err != nil {
return nil, fmt.Errorf("enable confirms: %w", err)
}
// The broker sends basic.return before basic.ack for a mandatory
// unroutable message, and the client enqueues it before resolving the ack.
returns := ch.NotifyReturn(make(chan amqp.Return, 1))
return &Publisher{ch: ch, returns: returns, exchange: exchange}, nil
}
// Publish satisfies es.PublishFunc.
func (p *Publisher) Publish(ctx context.Context, e es.Event) error {
dc, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, p.exchange, RoutingKey(e), true, false, Message(e))
if err != nil {
return err
}
acked, err := dc.WaitContext(ctx)
if err != nil {
return fmt.Errorf("confirm outcome unknown for %s: %w", e.EventID, err)
}
select {
case r := <-p.returns:
return fmt.Errorf("%w: %s %d %s", ErrUnroutable, r.MessageId, r.ReplyCode, r.ReplyText)
default:
}
if !acked {
return fmt.Errorf("%w: %s", ErrNacked, e.EventID)
}
return nil
}
// RoutingKey lets topic bindings select by event type, e.g. "account.MoneyWithdrawn".
func RoutingKey(e es.Event) string { return "account." + e.Type }
// Message maps an event to AMQP properties. MessageId carries the stable
// event ID that consumers deduplicate on; headers carry both positions.
func Message(e es.Event) amqp.Publishing {
return amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
MessageId: e.EventID,
Type: e.Type,
Timestamp: e.OccurredAt,
Headers: amqp.Table{
"stream_id": e.StreamID,
"stream_version": e.StreamVersion,
"global_position": e.GlobalPosition,
"schema_version": int32(e.SchemaVersion),
},
Body: e.Data,
}
}
// StreamConsumerArgs attaches a consumer to a RabbitMQ stream at an offset
// spec: "first", "last", "next", a numeric offset or a timestamp. Streams
// require a per-consumer prefetch (ch.Qos) and manual acknowledgements.
func StreamConsumerArgs(offset any) amqp.Table {
return amqp.Table{"x-stream-offset": offset}
}package rabbitrelay
import (
"testing"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"academy/event-sourcing-cqrs/es"
)
func TestMessageCarriesIdentityAndPositions(t *testing.T) {
e := es.Event{EventID: "cmd-9/0", StreamID: "acc-1", StreamVersion: 4, GlobalPosition: 812,
Type: es.TypeMoneyWithdrawn, SchemaVersion: 2, Data: []byte(`{"amount":30,"reason":"atm"}`),
OccurredAt: time.Unix(1, 0)}
m := Message(e)
if m.MessageId != "cmd-9/0" || m.DeliveryMode != amqp.Persistent || string(m.Body) != string(e.Data) {
t.Fatalf("message %+v", m)
}
if m.Headers["stream_version"] != int64(4) || m.Headers["global_position"] != int64(812) {
t.Fatalf("headers %+v", m.Headers)
}
if err := m.Headers.Validate(); err != nil {
t.Fatalf("headers not AMQP-encodable: %v", err)
}
if RoutingKey(e) != "account.MoneyWithdrawn" {
t.Fatal(RoutingKey(e))
}
}| نیاز | ابزار RabbitMQ | آنچه ندارد |
|---|---|---|
| fan-out قابل replay | stream و x-stream-offset | بررسی نسخه برای هر key |
| پذیرش بادوام | publisher confirms و پیام persistent | اتمیکبودن با پایگاه داده |
| تشخیص غیرقابلمسیریابی | mandatory و basic.return | هیچ، اگر mandatory=false (پیشفرض) |
| rebuild از موقعیت صفر | با retention قابل اتکا نیست | از event store استفاده کنید |
Kafka
key کردن رکوردها با stream ID رویدادهای یک حساب را درون یک partition مرتب نگه میدارد. Kafka برای آخرین offset یک key، append شرطی ندارد، پس نمیتواند expected version را اجبار کند: دو producer میتوانند هر دو «نسخهٔ ۸» را منتشر کنند. consumerها headerهای stream_version را بررسی میکنند و با شکاف متوقف میشوند (CheckVersion). compaction آخرین مقدار هر key را نگه میدارد و بنابراین replay تاریخچه را برای topicهای رویداد میشکند (ببینید Log compaction)؛ برای انتقال رویداد cleanup.policy=delete و برای topicهای آخرین وضعیت compact به کار ببرید و هنگام ساخت topic کد خطای هر topic را بررسی کنید.
Kafka transactions نوشتن در چند partition از Kafka را اتمیک میکند و در حلقههای consume-transform-produce offset مصرفکننده را هم شامل میشود؛ اما checkpoint relay در PostgreSQL را شامل نمیشود، پس relay همچنان at-least-once است. idempotent producer در franz-go (بهطور پیشفرض روشن) تکرارهای ناشی از retry داخلی کلاینت را حذف میکند، نه relayی که restart میشود و دوباره منتشر میکند.
// Package kafkarelay publishes the committed event feed to Kafka. Kafka is
// transport and a replay buffer here: it has no per-key expected-version
// check, so it cannot be the system of record for these streams.
package kafkarelay
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
"github.com/twmb/franz-go/pkg/kmsg"
"academy/event-sourcing-cqrs/es"
)
// Topic configurations. Values are strings, as Kafka expects.
var (
// Every event, keyed by stream ID. "delete" keeps all records until
// retention: compaction here would keep only the LAST event per account
// and destroy the history a consumer would replay.
EventTopicConfig = map[string]string{
"cleanup.policy": "delete",
"retention.ms": "604800000", // 7 days; PostgreSQL holds the full history
}
// Latest balance per account (event-carried state). Compaction fits:
// only the newest value per key matters. A null value is a tombstone.
LatestStateTopicConfig = map[string]string{
"cleanup.policy": "compact",
"min.compaction.lag.ms": "3600000", // keep at least 1 h of uncompacted head
"delete.retention.ms": "86400000", // tombstones visible for 1 day
}
)
var ErrTopicExists = errors.New("topic already exists: verify its configuration")
// CreateTopic creates one topic and checks the per-topic error code, which a
// successful request can still carry.
func CreateTopic(ctx context.Context, cl *kgo.Client, name string, partitions int32, rf int16, cfg map[string]string) error {
req := kmsg.NewPtrCreateTopicsRequest()
req.TimeoutMillis = 30000
t := kmsg.NewCreateTopicsRequestTopic()
t.Topic, t.NumPartitions, t.ReplicationFactor = name, partitions, rf
for k, v := range cfg {
c := kmsg.NewCreateTopicsRequestTopicConfig()
c.Name, c.Value = k, kmsg.StringPtr(v)
t.Configs = append(t.Configs, c)
}
req.Topics = append(req.Topics, t)
resp, err := req.RequestWith(ctx, cl)
if err != nil {
return err
}
if len(resp.Topics) != 1 {
return fmt.Errorf("create %s: %d topic results", name, len(resp.Topics))
}
switch err := kerr.ErrorForCode(resp.Topics[0].ErrorCode); {
case err == nil:
return nil
case errors.Is(err, kerr.TopicAlreadyExists):
return fmt.Errorf("%w: %s", ErrTopicExists, name)
default:
return fmt.Errorf("create %s: %w", name, err)
}
}
// Record keys by stream ID: one account's events share a partition and keep
// their order. Headers carry what consumers need to detect gaps and duplicates.
func Record(topic string, e es.Event) *kgo.Record {
return &kgo.Record{
Topic: topic,
Key: []byte(e.StreamID),
Value: e.Data,
Headers: []kgo.RecordHeader{
{Key: "event_id", Value: []byte(e.EventID)},
{Key: "event_type", Value: []byte(e.Type)},
{Key: "schema_version", Value: []byte(strconv.Itoa(e.SchemaVersion))},
{Key: "stream_version", Value: []byte(strconv.FormatInt(e.StreamVersion, 10))},
{Key: "global_position", Value: []byte(strconv.FormatInt(e.GlobalPosition, 10))},
},
Timestamp: e.OccurredAt,
}
}
// Publisher returns an es.PublishFunc. franz-go enables the idempotent
// producer by default, which removes broker-side duplicates from internal
// retries; it does not dedupe a relay that restarts and republishes.
func Publisher(cl *kgo.Client, topic string) es.PublishFunc {
return func(ctx context.Context, e es.Event) error {
return cl.ProduceSync(ctx, Record(topic, e)).FirstErr()
}
}
// PublishWithState writes the event and the new latest-state value in one
// Kafka transaction (client built with kgo.TransactionalID). Atomic for the
// two Kafka topics only; the PostgreSQL relay checkpoint is a separate write.
func PublishWithState(ctx context.Context, cl *kgo.Client, eventTopic, stateTopic string, e es.Event, state []byte) error {
if err := cl.BeginTransaction(); err != nil {
return err
}
st := &kgo.Record{Topic: stateTopic, Key: []byte(e.StreamID), Value: state}
if err := cl.ProduceSync(ctx, Record(eventTopic, e), st).FirstErr(); err != nil {
if abortErr := cl.EndTransaction(ctx, kgo.TryAbort); abortErr != nil {
return errors.Join(err, abortErr)
}
return err
}
return cl.EndTransaction(ctx, kgo.TryCommit)
}
// ErrVersionGap means a consumer saw stream_version n+2 after n: resync
// that stream from the event store instead of guessing.
var ErrVersionGap = errors.New("stream version gap")
// Decision is what a consumer should do with one record.
type Decision int
const (
Apply Decision = iota
Duplicate // already applied: acknowledge and skip
)
// CheckVersion compares a record's stream_version with the last version the
// consumer applied for that key (stored next to its read model).
func CheckVersion(lastApplied int64, rec *kgo.Record) (Decision, int64, error) {
var v int64 = -1
for _, h := range rec.Headers {
if h.Key == "stream_version" {
parsed, err := strconv.ParseInt(string(h.Value), 10, 64)
if err != nil {
return 0, 0, err
}
v = parsed
}
}
switch {
case v < 1:
return 0, 0, errors.New("missing stream_version header")
case v <= lastApplied:
return Duplicate, v, nil
case v == lastApplied+1:
return Apply, v, nil
default:
return 0, v, fmt.Errorf("%w: key %s last %d got %d", ErrVersionGap, rec.Key, lastApplied, v)
}
}package kafkarelay
import (
"errors"
"testing"
"academy/event-sourcing-cqrs/es"
)
func TestRecordAndVersionCheck(t *testing.T) {
e := es.Event{EventID: "c/0", StreamID: "acc-1", StreamVersion: 5, GlobalPosition: 99,
Type: es.TypeMoneyDeposited, SchemaVersion: 1, Data: []byte(`{"amount":7}`)}
rec := Record("account-events", e)
if string(rec.Key) != "acc-1" {
t.Fatalf("key %q", rec.Key)
}
cases := []struct {
last int64
want Decision
gap bool
}{{4, Apply, false}, {5, Duplicate, false}, {9, Duplicate, false}, {3, 0, true}}
for _, c := range cases {
d, v, err := CheckVersion(c.last, rec)
if c.gap != errors.Is(err, ErrVersionGap) || (!c.gap && (d != c.want || v != 5)) {
t.Errorf("last=%d: d=%v v=%d err=%v", c.last, d, v, err)
}
}
}
func TestConfigsMatchPurpose(t *testing.T) {
if EventTopicConfig["cleanup.policy"] != "delete" {
t.Error("event history topic must not be compacted")
}
if LatestStateTopicConfig["cleanup.policy"] != "compact" {
t.Error("latest-state topic should be compacted")
}
}| نیاز | ابزار Kafka | آنچه ندارد |
|---|---|---|
| ترتیب هر stream | key به partition | ترتیب بین partitionها |
| expected version | ندارد | باید در store بررسی شود |
| آخرین وضعیت | cleanup.policy=compact و tombstone | تاریخچهٔ کامل |
| نوشتن اتمیک در چند topic | transactions (transactional.id) | پایگاه دادهٔ بیرونی در همان تراکنش |
Redis Streams
XADD با ID صریح، IDی بزرگتر از مدخل بالای stream میخواهد و در غیر این صورت با پیام «The ID specified in XADD is equal or smaller than the target stream top item» شکست میخورد. استفاده از global position بهعنوان ID (812-0) relay را مرتب و تکرارهایش را قابل تشخیص میکند: پس از آن خطا، relay مدخل را با XRANGE میخواند و فقط اگر event_id ذخیرهشده یکی باشد آن را میپذیرد، چون خود خطا ثابت نمیکند آن ID وجود دارد. این CAS روی نسخهٔ stream یک حساب نیست؛ دو نویسندهٔ رویدادهای حسابهای مختلف هر دو موفق میشوند. replay از بازههای انحصاری استفاده میکند (XRANGE key (812-0 +، Redis 6.2 به بعد). اگر consumerی به تاریخچهٔ کامل تکیه دارد با MAXLEN یا MINID کوتاه نکنید و به یاد داشته باشید دوام به تنظیمات AOF/RDB بستگی دارد (appendfsync everysec ممکن است حدود یک ثانیه نوشتن را از دست بدهد).
// Package redisrelay copies the committed event feed into a Redis stream
// whose entry IDs equal the PostgreSQL global position. Explicit IDs make the
// relay idempotent and ordered; they are NOT an expected-version check for an
// account stream, which only PostgreSQL performs.
package redisrelay
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/redis/go-redis/v9"
"academy/event-sourcing-cqrs/es"
)
var ErrDiverged = errors.New("redis stream holds a different entry at this ID")
// EntryID maps global position p to "p-0". XADD requires each explicit ID to
// be greater than the stream's top ID, so the feed order is enforced by Redis.
func EntryID(e es.Event) string { return strconv.FormatInt(e.GlobalPosition, 10) + "-0" }
// Values are flat field/value pairs; Data stays the raw JSON payload.
func Values(e es.Event) map[string]any {
return map[string]any{
"event_id": e.EventID,
"stream_id": e.StreamID,
"stream_version": e.StreamVersion,
"type": e.Type,
"schema_version": e.SchemaVersion,
"data": string(e.Data),
}
}
// Publisher returns an es.PublishFunc. There is deliberately no MAXLEN or
// MINID: a consumer that replays this stream would silently miss trimmed
// history. If you trim, consumers must resync from PostgreSQL instead.
func Publisher(rdb *redis.Client, key string) es.PublishFunc {
return func(ctx context.Context, e es.Event) error {
err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: key, ID: EntryID(e), Values: Values(e)}).Err()
if err == nil || !IDTooSmall(err) {
return err
}
// Retry after a lost reply, or a second relay: the ID may already be
// there. "Equal or smaller" alone does not prove it is OUR entry.
got, rerr := rdb.XRange(ctx, key, EntryID(e), EntryID(e)).Result()
if rerr != nil {
return errors.Join(err, rerr)
}
return SameEntry(got, e)
}
}
// IDTooSmall recognises Redis's rejection of a non-increasing explicit ID.
func IDTooSmall(err error) bool {
return err != nil && strings.Contains(err.Error(), "equal or smaller than the target stream top item")
}
// SameEntry accepts a duplicate only when the stored entry has our event ID.
func SameEntry(got []redis.XMessage, e es.Event) error {
if len(got) == 1 && got[0].ID == EntryID(e) && got[0].Values["event_id"] == e.EventID {
return nil
}
return fmt.Errorf("%w: %s", ErrDiverged, EntryID(e))
}
// ReadAfter replays entries strictly after lastID, using the exclusive "("
// range prefix (Redis 6.2+). Use "0-0" to start from the beginning.
func ReadAfter(ctx context.Context, rdb *redis.Client, key, lastID string, count int64) ([]redis.XMessage, error) {
return rdb.XRangeN(ctx, key, "("+lastID, "+", count).Result()
}package redisrelay
import (
"errors"
"testing"
"github.com/redis/go-redis/v9"
"academy/event-sourcing-cqrs/es"
)
func TestEntryIDAndDuplicateResolution(t *testing.T) {
e := es.Event{EventID: "c/0", StreamID: "acc-1", GlobalPosition: 812}
if EntryID(e) != "812-0" {
t.Fatal(EntryID(e))
}
ours := []redis.XMessage{{ID: "812-0", Values: map[string]any{"event_id": "c/0"}}}
if err := SameEntry(ours, e); err != nil {
t.Fatalf("own duplicate rejected: %v", err)
}
theirs := []redis.XMessage{{ID: "812-0", Values: map[string]any{"event_id": "other/0"}}}
if err := SameEntry(theirs, e); !errors.Is(err, ErrDiverged) {
t.Fatalf("foreign entry accepted: %v", err)
}
if err := SameEntry(nil, e); !errors.Is(err, ErrDiverged) {
t.Fatal("missing entry accepted: top ID is larger but 812-0 was never written")
}
if !IDTooSmall(errors.New("ERR The ID specified in XADD is equal or smaller than the target stream top item")) {
t.Fatal("redis error not recognised")
}
}| نیاز | ابزار Redis | آنچه ندارد |
|---|---|---|
| relay مرتب | IDهای صریح صعودی | بررسی نسخه برای هر aggregate |
| Replay | XRANGE / XREAD از یک ID | تاریخچه پس از کوتاهسازی |
| consumer group | XREADGROUP و XACK | معنای rebuild |
| دوام | سیاست appendfsync در AOF | replication همگام بهطور پیشفرض |
محصولات دیگر
| محصول | ابزار مرتبط | تناسب برای event store |
|---|---|---|
| KurrentDB (EventStoreDB) | stream، expected revision، $all، $maxAge / $maxCount | store ساختهشده برای همین کار |
| NATS JetStream | Nats-Expected-Last-Subject-Sequence و پنجرهٔ deduplication با Nats-Msg-Id | همروندی خوشبینانه برای هر subject وجود دارد |
| Apache Pulsar | topic compaction جدا از retention که retention را رعایت میکند | همان هشدار compaction در Kafka |
| Amazon SQS FIFO | بازهٔ deduplication پنجدقیقهای | صف است، نه store |
در سیستمهای واقعی
- مستند PostgreSQL میگوید مقدارهای
nextvalهرگز rollback نمیشوند و sequence شمارهگذاری بدون شکاف نمیدهد؛ همین دلیل ناامنبودن cursor مبتنی برbigserialبرای projection است. - مستند async daemon در Marten، high water mark را توضیح میدهد که زیر حفرههای sequence رویداد میایستد و حفره را فقط وقتی رد میکند که هیچ تراکنش در حال اجرایی نتواند پرش کند، و حالت
QuickAppendرا که احتمال شکاف را کم میکند. - مستند stream در KurrentDB حذف نرم با
TruncateBefore، حذف سخت با tombstone از نوع$streamDeleted، تنظیمات$maxAge/$maxCountو scavenging را که رویدادها را بهطور فیزیکی پاک میکند شرح میدهد. - مستند طراحی Kafka تضمینهای compaction و سقف
delete.retention.msبرای tombstoneها را فهرست میکند؛ مرجع پیکربندی topic پیشفرضcleanup.policyراdeleteمیداند.
در معماری: از یک فرایند تا سیستم توزیعشده
یکپارچه (Monolith): یک فرایند و یک پایگاه داده
با store، یک projection درون همان فرایند (inline یا ناهمگام) و read-your-writes از طریق token شروع کنید. مثال: ماژول کیف پول در یک monolith لاراولی از کنترلرها EventStore::execute را صدا میزند و هر ثانیه از یک فرمان زمانبندیشده BalanceProjector::project('balances_v1') را اجرا میکند؛ صفحهٔ موجودی مقدار atLeast را از آخرین پاسخ میفرستد.
یکپارچهٔ ماژولار (Modular monolith): مالکیت صریح
هر ماژول مالک streamها و projectionهای خودش است؛ ماژولهای دیگر read modelهای عمومی را میخوانند یا از طریق relay داخلی مشترک feed میشوند و هرگز مستقیماً ردیفهای events ماژول دیگر را query نمیکنند. مثال: ماژول payments مالک streamهای acc-* است؛ reporting مالک monthly_statements_v3 است که از feed مشترک ساخته میشود و چیدمان جدید صورتحساب بهشکل v4 با روش blue/green منتشر میشود.
میکروسرویسها (Microservices): آنچه از مرز عبور میکند
event store و بررسی expected version درون یک سرویس میمانند. سرویسهای دیگر رویدادهای یکپارچهسازی را از طریق relay با تأیید broker میگیرند، با event ID تکرار را حذف میکنند و نمیتوانند ترتیب سراسری بین سرویسها را فرض کنند. مثال: wallet رویداد MoneyWithdrawn را append میکند و قرارداد AccountDebited را با key حساب به Kafka میفرستد؛ fraud آن را مصرف میکند، stream_version را برای هر key بررسی میکند و وضعیت خودش را نگه میدارد؛ برداشت مورد اعتراض در wallet به WithdrawalReversed و یک رویداد یکپارچهسازی جداگانهٔ AccountCredited تبدیل میشود. سازگاری بین سرویسها با saga است، نه یک event store مشترک.
دادهٔ توزیعشده (Distributed data): replica، shard و region
replica عقب میماند: projectorی که از replica میخواند ترتیب commit را میبیند، اما دیرتر؛ tokenهای read-your-writes باید با checkpoint projection روی همان replica مقایسه شوند، نه با head روی primary. تقسیم streamها بین چند پایگاه داده برای هر shard یک feed میدهد؛ consumerها موقعیتهای هر shard را با هم ترکیب میکنند و هرگز ترتیب کامل نمیگیرند. appendهای active-active چند regionی به یک stream به consensus یا یک region خانگی برای هر stream نیاز دارند؛ replication ناهمگام چند-master نمیتواند expected version را اجبار کند.
مسیر مقیاس (Scaling path)
| بار | طراحی |
|---|---|
| ۱× (دهها append در ثانیه) | یک PostgreSQL، قفل allocator، projector ناهمگام درون فرایند |
| ۱۰× (صدها در ثانیه) | دستهکردن رویدادها در هر command، تراکنش کوتاه، یک projector برای هر read model، snapshot برای streamهای طولانی، اندازهگیری انتظار روی allocator |
| ۱۰۰× (هزارها در ثانیه) | جایگزینی allocator با تشخیص شکاف یا CDC مبتنی بر logical decoding، shard کردن streamها با key یا یک store اختصاصی؛ projectionها با تقسیم بر اساس stream ID مقیاس میگیرند |
آزمایشگاه
برای همهٔ مراحل پایگاه داده و broker: «خروجی موردانتظار؛ اجرا نشده». هیچ Docker، پایگاه داده یا brokerی راهاندازی نشد. اگر PostgreSQL یکبارمصرف دارید از آن استفاده کنید؛ آزمونهای واحد Go بدون آن اجرا میشوند.
1. اجرای آزمونهای خالص
cd docs/snippets/messaging/event-sourcing-cqrs/go
go test ./...
# ok academy/event-sourcing-cqrs/es
# ok academy/event-sourcing-cqrs/brokers/kafka (rabbitmq, redisstreams likewise)2. دیدن سریالیشدن دو append توسط allocator
1 psql A -> BEGIN; SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE; -- 1
2 psql B -> BEGIN; SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE; -- waits
3 psql A -> UPDATE feed_allocator SET next_position = 2 WHERE id = 1; COMMIT;
4 psql B -> returns 2 (the updated row, Read Committed re-check)خروجی موردانتظار؛ اجرا نشده. همین را با ROLLBACK در گام ۳ تکرار کنید: B مقدار ۱ را برمیگرداند و شکافی ایجاد نمیشود.
3. بازتولید جاافتادن با bigserial (در جدول آزمایشی)
CREATE TABLE seq_demo (pos bigserial PRIMARY KEY, note text);
-- psql A: BEGIN; INSERT INTO seq_demo (note) VALUES ('slow') RETURNING pos; -- 1, keep open
-- psql B: INSERT INTO seq_demo (note) VALUES ('fast') RETURNING pos; -- 2, autocommit
-- psql C: SELECT pos FROM seq_demo WHERE pos > 0 ORDER BY pos; -- 2 only
-- psql A: COMMIT; a reader that stored checkpoint 2 never reads pos 14. تکرار فرمان پس از commit نامعلوم
Execute را دو بار با همان CommandID و همان نیت صدا بزنید: بار دوم انتظار {StreamVersion: 3, LastPosition: 812, Duplicate: true} و فقط یک ردیف در events را داریم. مبلغ را عوض کنید و ID را نگه دارید: انتظار ErrCommandIDReused. خروجی موردانتظار؛ اجرا نشده.
5. rebuild به روش blue/green
1 Project("balances_v2", 500) in a loop until it returns 0
2 head := Head(); ActivateProjection("balances", "balances_v2", head)
3 QueryBalance("acc-42", token) -> AsOf >= token
4 Insert an AccountFrozen v1 row by hand in a scratch DB -> Project returns ErrUnknownEvent, checkpoint unchanged6. بررسیهای broker
kafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type topics --entity-name account-events
# expected, not run: cleanup.policy=delete
redis-cli XADD acct-feed 812-0 event_id c-77/0
redis-cli XADD acct-feed 812-0 event_id c-77/0
# expected, not run: (error) ERR The ID specified in XADD is equal or smaller than the target stream top item
rabbitmqctl list_queues name type messages
# expected, not run: account-feed stream ...بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| CQRS به event sourcing نیاز دارد | CQRS مدلها را جدا میکند؛ مدل query میتواند view در همان پایگاه داده باشد |
| CQRS یعنی eventual consistency | مدل query در همان تراکنش فوراً سازگار است |
| event sourcing به Kafka نیاز دارد | store به append با expected version و ترتیب بدون شکاف نیاز دارد؛ PostgreSQL هر دو را میدهد |
bigserial ترتیب feed را میدهد | مقدارها پیش از commit تخصیص مییابند و ممکن است نامرتب قابلدیدن شوند |
| expected version تکرار را idempotent میکند | جلوی نوشتن همزمان را میگیرد؛ تکرار به command receipt نیاز دارد |
| snapshot حقیقت است | cacheی دورریختنی از تاریخچهٔ commitشده است |
| projector باید رویداد ناشناخته را رد کند | رد کردن واقعیت را برای همیشه گم میکند؛ fail closed |
| rebuild یعنی truncate و replay | خواننده دادهٔ ناقص میبیند؛ از projection نسخهدار استفاده کنید |
| topic فشردهشده event store است | compaction فقط آخرین رکورد هر key را نگه میدارد |
| IDهای صریح Redis همروندی خوشبینانه میدهند | IDهای صعودی را برای هر key اجبار میکنند، نه نسخهٔ هر aggregate |
| لاگ تغییرناپذیر نمیتواند داده را حذف کند | crypto-shredding، retention و حذف وجود دارند، با کپیهایی که باید پیگیری شوند |
| crypto-shredding انطباق قانونی را تضمین میکند | فقط یک store را پوشش میدهد؛ انطباق به فهرست کامل داده و بررسی حقوقی نیاز دارد |
| بانکها موجودی نگه نمیدارند و فقط رویداد دارند | برخی دفترکلها چنیناند؛ این تشبیه است، نه واقعیتی همگانی |
چکیدهٔ سریع
| موضوع | به خاطر بسپارید |
|---|---|
| Append | قفل allocator ← receipt ← fold ← decide ← CAS ← درج ← جلو بردن ← receipt ← COMMIT |
| Expected version | AnyVersion، NoStream، عدد دقیق؛ تکرار با نسخهٔ جدید و همان command ID |
| Global position | بدون شکاف و به ترتیب commit؛ قفل allocator، تشخیص شکاف یا CDC |
| Load | REPEATABLE READ فقطخواندنی؛ snapshot اعتبارسنجیشده؛ نسخهٔ نهایی برابر head |
| Snapshot | از تاریخچهٔ commitشده؛ نسخهٔ قالب؛ هرگز جدیدتر را بازنویسی نکنید |
| Projection | ردیفها و checkpoint در یک تراکنش؛ stream_version = v - 1؛ ردیف تغییرکرده = ۱ |
| رویداد ناشناخته | توقف؛ استقرار خوانندهٔ مناسب؛ اجرای دوباره |
| Rebuild | نسخهٔ جدید projection، رسیدن، فعالسازی در head، حذف قدیمی بعداً |
| Upcasting | خالص، هنگام خواندن، decode سختگیرانه، آزمون برای هر نسخه |
| Read-your-writes | موقعیت را برگردانید؛ query با atLeast؛ صبر یا بازگشت به مدل نوشتن |
| اصلاحها | رویداد جبرانی؛ event time در برابر processing time |
| حریم خصوصی | مُهر برای هر صاحب داده؛ نابودی کلید؛ فهرست همهٔ کپیها |
| Kafka | key برابر stream؛ CAS ندارد؛ delete برای رویداد، compact برای وضعیت |
| RabbitMQ | stream برای replay؛ confirms و mandatory |
| Redis Streams | ID صریح یعنی relay مرتب، نه CAS؛ اگر replay به تاریخچه تکیه دارد کوتاه نکنید |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا cursor مبتنی بر bigserial حتی بدون rollback رویداد گم میکند؟ مهم
پاسخ
پاسخ: مقدار هنگام درج تخصیص مییابد. تراکنشی با مقدار کوچکتر ممکن است بعد از تراکنشی با مقدار بزرگتر commit شود؛ خوانندهای که بزرگتر را دیده و بهعنوان checkpoint ذخیره کرده، کوچکتر را هرگز نمیخواند.
۲ — قفل allocator چه هزینهای دارد و چه جایگزینهایی هست؟ تکمیلی
پاسخ
پاسخ: همهٔ appendها پشت یک قفل ردیف سریالی میشوند. جایگزینها تشخیص شکاف با high water mark (مثل Marten) یا خواندن تغییرات commitشده با CDC مبتنی بر logical decoding هستند.
۳ — چرا expected version برای تکرار کلاینت کافی نیست؟ مهم
پاسخ
پاسخ: اگر تلاش اول commit شده اما پاسخ گم شده باشد، تکرار در CAS شکست میخورد، کلاینت دوباره بارگذاری میکند و ممکن است همان نیت را دوباره تصمیم بگیرد. command receipt بهجای آن نتیجهٔ ذخیرهشده را برمیگرداند.
۴ — snapshot چه وقت هنگام بارگذاری قابل اعتماد است؟ مهم
پاسخ
پاسخ: وقتی قالبش با کد فعلی جور باشد، stream ID آن مطابقت کند، نسخهاش حداکثر برابر head commitشده باشد و از رویدادهای commitشده ساخته شده باشد. در غیر این صورت از ابتدا replay کنید.
۵ — چرا projection باید ردیفها و checkpoint را در یک تراکنش بهروز کند؟ حیاتی
پاسخ
پاسخ: وگرنه خرابی بین این دو، هنگام راهاندازی دوباره یا دسته را جا میاندازد (اول checkpoint) یا دو بار اعمال میکند (اول ردیفها).
۶ — projector به MoneyWithdrawn نسخهٔ ۳ میرسد اما فقط نسخهٔ ۲ را میشناسد. چه باید بکند؟ تکمیلی
پاسخ
پاسخ: بدون جلو بردن checkpoint متوقف شود، هشدار دهد، buildی که نسخهٔ ۳ را میفهمد مستقر شود و دوباره اجرا کند. رد کردن رویداد را گم میکند.
۷ — آیا سیستمی که روی یک PostgreSQL، handlerهای جدا برای command و query دارد CQRS است؟ حیاتی
پاسخ
پاسخ: بله. CQRS جداسازی مدلهاست؛ رویداد، broker، پایگاه دادهٔ جدا و eventual consistency اختیاریاند.
۸ — چطور read model را بدون نشاندادن جدول نیمهخالی به کاربر بازسازی کنیم؟ مهم
پاسخ
پاسخ: نسخهٔ جدیدی از projection با ردیفها و checkpoint خودش بسازید، بگذارید عقبماندگی را جبران کند، وقتی checkpoint آن به head رسید فعالش کنید و نسخهٔ قدیمی را بعداً حذف کنید.
۹ — چرا topic فشردهشدهٔ Kafka نمیتواند جای event store را بگیرد؟ حیاتی
پاسخ
پاسخ: compaction فقط آخرین رکورد هر key را نگه میدارد، پس replay از ابتدا مقدار نهایی را میدهد نه دنبالهٔ واقعیتها را. Kafka همچنین بررسی expected version ندارد.
۱۰ — حذف کلید یک صاحب داده چه چیزی را به دست میدهد و چه چیزی را نه؟ تکمیلی
پاسخ
پاسخ: فیلدهای مُهرشدهٔ آن فرد در همهٔ ردیفهای رویداد ناخوانا میشوند. کپیهای متن ساده در read modelها، لاگها، cacheها، ایندکسهای جستوجو، topicهای broker و پشتیبانهای جدول کلید تحت تأثیر قرار نمیگیرند.
۱۱ — چرا relay در Redis پس از خطای «equal or smaller» مدخل را دوباره میخواند؟ تکمیلی
پاسخ
پاسخ: آن خطا فقط میگوید ID از بالای stream بزرگتر نیست. مدخل ممکن است مال ما باشد (انتشار تکراری) یا هرگز نوشته نشده باشد؛ فقط بررسی event_id با XRANGE مشخص میکند کدام است.
واژهنامه
| اصطلاح | معنا |
|---|---|
| رویداد (Event) | واقعیت تغییرناپذیر در زمان گذشته |
| منبعیابی رویداد (Event sourcing) | ذخیرهٔ رویدادها بهعنوان منبع حقیقت و ساخت وضعیت با fold آنها |
| Event store | پایگاه دادهٔ streamها با append مبتنی بر expected version و خواندن مرتب |
| Stream | رویدادهای مرتب یک aggregate با نسخههای 1..n |
| Aggregate | مرز سازگاری که یک stream قواعد ثابتش را حفظ میکند |
| فقطافزودنی (Append-only) | ردیفها در کار عادی درج میشوند و هرگز بهروز یا حذف نمیشوند |
| Expected version | نسخهای که append از stream انتظار دارد |
| همروندی خوشبینانه (Optimistic concurrency) | تشخیص نوشتن متعارض هنگام commit بهجای قفل در زمان تصمیم |
| Global position | شمارهای بدون شکاف و به ترتیب commit روی همهٔ streamها |
| Feed allocator | تنها ردیف قفلشونده که در این store موقعیت سراسری میدهد |
| High water mark | بالاترین موقعیتی در Marten که همهٔ رویدادهای زیرش commitشده شناخته میشوند |
| Decide / evolve (fold) | تابع خالص تصمیم / گذار خالص وضعیت برای هر رویداد |
| بازپخش (Replay) | اجرای دوبارهٔ رویدادها برای بازسازی وضعیت یا read model |
| Snapshot (rolling snapshot) | وضعیت cacheشده در یک نسخهٔ stream برای کوتاهکردن بارگذاری |
| Projection | کدی که رویدادها را به read model تبدیل میکند |
| Read model | دادهٔ بهینهشده برای query که از رویدادها مشتق میشود |
| Checkpoint | آخرین global position که projection یا relay پردازش کرده است |
| Live / inline / async projection | fold هنگام خواندن / همان تراکنش / پسزمینه با checkpoint |
| بازسازی (Rebuild) | محاسبهٔ دوبارهٔ read model از تاریخچهٔ رویدادها |
| Blue/green projection | نسخهٔ جدید projection که کنار قدیمی ساخته و سپس جایگزین میشود |
| Fail closed | توقف پردازش با ورودی ناشناخته یا ناسازگار |
| نسخهبندی رویداد (Event versioning) | نوع و نسخهٔ اسکیما روی هر رویداد |
| Upcaster / upcasting | تبدیل شکل قدیمی رویداد به شکل فعلی هنگام خواندن |
| CQRS | مدلهای جدا برای command و query |
| فرمان (Command) | درخواست تغییر وضعیت که ممکن است رد شود |
| پرسوجو (Query) | درخواست داده که چیزی را تغییر نمیدهد |
| سازگاری نهایی (Eventual consistency) | read model پس از تأخیری همگرا میشود |
| Read-your-writes | کلاینت نوشتههای کاملشدهٔ خودش را میبیند |
| Read-your-writes token | موقعیتی که نوشتن برمیگرداند و خواندن لازمش دارد |
| Idempotency | تکرار یک عملیات اثر اضافهای ندارد |
| Command receipt | command ID، fingerprint و نتیجهٔ ذخیرهشده |
| Fingerprint | هش نیت یک فرمان، بدون ID آن |
| Event time / processing time | کی رخ داد / کی سیستم ثبتش کرد |
| رویداد جبرانی (Compensating event) | رویداد جدیدی که اثر رویداد قبلی را برمیگرداند |
| Retroactive event / bi-temporal | اصطلاحات فاولر برای تغییر واقعیتهای گذشته و مدلکردن دو محور زمان |
| Crypto-shredding | نابودی کلید هر صاحب داده برای ناخوانا کردن دادهٔ مُهرشده |
| Tombstone | نشانهٔ حذف: رکورد با مقدار null در Kafka، $streamDeleted در KurrentDB |
| TruncateBefore / scavenging | فرادادهٔ حذف نرم در KurrentDB / فرایند حذف فیزیکی |
| Log compaction | نگهداری در Kafka که آخرین رکورد هر key را نگه میدارد |
cleanup.policy | تنظیم topic در Kafka: delete، compact یا هر دو |
delete.retention.ms / min.compaction.lag.ms | سقف دیدهشدن tombstone / حداقل عمر فشردهنشده |
| Kafka transactions | نوشتن اتمیک در چند partition از Kafka، بهطور اختیاری همراه offset مصرفکننده |
| Idempotent producer | قابلیت producer در Kafka که تکرارهای retry داخلی را حذف میکند |
| RabbitMQ Streams | نوع صف append-only و غیرمخرب در RabbitMQ |
x-stream-offset / x-max-age | نقطهٔ شروع consumer در stream / retention stream |
| Publisher confirms | تأیید broker که پیام منتشرشده پذیرفته شده است |
mandatory / basic.return | پرچم انتشار / بازگرداندن پیام غیرقابلمسیریابی توسط broker |
XADD / XRANGE | افزودن در Redis با ID صریح اختیاری / خواندن بازه |
MAXLEN / MINID | گزینههای کوتاهسازی stream در Redis |
Nats-Expected-Last-Subject-Sequence | header همروندی خوشبینانه برای هر subject در NATS JetStream |
| EventStoreDB/Kurrent | KurrentDB، با نام قبلی EventStoreDB، پایگاه دادهٔ ساختهشده برای streamهای رویداد |
| Marten | کتابخانهٔ .NET که PostgreSQL را به document store و event store تبدیل میکند |
| Axon | Axon Framework، چارچوب JVM برای CQRS و event sourcing |
| spatie/laravel-event-sourcing | بستهٔ Laravel با aggregate، projector و reactor |
| Reactor | handler اثر جانبی در Spatie که هنگام replay فراخوانده نمیشود |
| Outbox | انتشار مطمئن مبتنی بر جدول، فصل outbox را ببینید |
| Fowler | مارتین فاولر، نویسندهٔ مقالهٔ Event Sourcing و یادداشت CQRS |
| Greg Young | نویسندهٔ CQRS Documents که CQRS را همراه event sourcing رایج کرد |
| SQLSTATE 40001 / 23505 | شکست serialization / نقض یکتایی در PostgreSQL |
منابع
- Martin Fowler: Event Sourcing، CQRS.
- Greg Young: CQRS Documents (PDF)، صفحهٔ مستندات.
- KurrentDB: Appending events، Event streams and deletion.
- Marten: Projections، Async daemon، Rebuilding projections، Event versioning.
- Axon Framework: Event snapshots (4.11)، Event versioning (5.0).
- spatie/laravel-event-sourcing v7: Introduction، Installation، First aggregate، Configuring aggregates، Snapshots، Replaying events، Projectors.
- PostgreSQL: Sequence functions، Explicit locking، Transaction isolation، INSERT / ON CONFLICT، SELECT locking clause، Error codes.
- Apache Kafka 4.4: Design (log compaction, transactions)، Topic configs.
- RabbitMQ: Streams، Publisher confirms، Publishers.
- Redis: Streams، XADD، XRANGE، XTRIM، Persistence.
- brokerهای دیگر: NATS JetStream headers، Pulsar topic compaction، SQS FIFO exactly-once processing.
- Laravel 13: Database، Query Builder.
- Go: database/sql، amqp091-go، franz-go kgo، go-redis.