Event sourcing asks you to stop overwriting your data. In a traditional CRUD application, updating a user’s shipping address means finding the row, changing the value, and discarding the previous state. Event sourcing takes a different path. It stores each change as an immutable fact: a user created an account, updated their address, verified their email. The current state of the system is not stored directly. It is computed by replaying these events in order.
This pattern solves real problems. Audit trails become free byproducts. You can reconstruct the state of an order at any past moment. You can debug by replaying exactly what happened. The trade-off is complexity. You now manage streams of facts, read models, and eventual consistency instead of simple rows.
PostgreSQL can act as your event store. Most teams already run it. It offers ACID transactions, JSONB for flexible payloads, and proven backup tools. You do not need to introduce Kafka, Cassandra, or a specialized event-store database on day one. A standard Postgres instance gives you the transactional guarantees and audit trails that event sourcing demands without expanding your infrastructure footprint.
The Shape of a Postgres Event Store
The schema can be almost embarrassingly simple. At minimum, you need a table that appends events and never updates them in place. A practical design looks like this:
idas a bigserial or UUID, serving as the global ordering.stream_idto group related events, such as all changes for a single user or order.event_typeas plain text:UserEmailChanged,PaymentReceived,InventoryAdjusted.payloadas JSONB, holding the specific data for that occurrence.occurred_atwith timezone precision.versionper stream, enforcing optimistic concurrency.
You enforce the immutability rule in application code or with a database constraint. A unique index on (stream_id, version) prevents two writers from appending the same sequence number. When a command comes in, you read the current version for that stream, increment it, and insert the new event inside a transaction. If another process beat you to it, the unique constraint fails, and you retry or reject the command.
Consider a concrete example. You run an inventory system. Instead of a single inventory row with a quantity column, you append events to a inventory_events table. ItemReceived adds ten units. ItemReserved removes two. ItemShipped removes three. To know the current stock for SKU-42, you sum the relevant event payloads. To know the stock three days ago, you sum only up to that timestamp. If a bug in your shipping logic caused an error last Tuesday, you replay the events through corrected code to get the true state. You cannot do that with a simple UPDATE statement.
Principles That Keep You Out of Trouble
Building on Postgres does not remove the need for discipline. The following principles apply directly to event-sourced systems.
Keep it simple. Complexity kills reliability. Resist the urge to build a generic event framework before you have shipped one working flow. A single table, a repository function to append events, and a projection worker to build read models are enough to prove value. Add tools only when a concrete problem appears.
Start small. Do not rewrite your entire monolith. Pick one bounded context where the audit trail pays for the overhead. A billing ledger, a workflow engine, or an inventory reservation system are good candidates. Build that one pipeline end-to-end. Let it run in production. Then decide whether to expand.
Define success first. Event sourcing is not a default architecture; it is a solution to specific needs. If your requirement is only to track the latest state, CRUD is faster and cheaper. If you need temporal queries, strict auditability, or the ability to rebuild read models on demand, then events make sense. Know which problem you are solving before you commit.
Measure before you optimize. Modern PostgreSQL on modest hardware can ingest thousands of events per second with a simple append-only table. Do not shard your event store or introduce complex partitioning schemes until your monitoring proves you have exhausted simpler fixes. Index the fields you query. Tune autovacuum for append-only workloads. Then measure again.
Teste tudo. Realize testes unitários em seus event handlers. Realize testes de integração no caminho de append. O mais importante: teste cenários de falha. O que acontece quando dois nós fazem append no mesmo stream simultaneamente? O que acontece quando um worker de projeção trava no meio de um batch? Escreva testes que verifiquem sua concorrência otimista e suas garantias de entrega at-least-once.
Monitore em produção. A tabela de eventos crescerá. Ao contrário de um esquema normalizado, onde as atualizações mantêm o número de linhas estável, o event sourcing é intencionalmente aditivo. Acompanhe o tamanho da tabela, o I/O de disco e o lag entre seu modelo de escrita e suas projeções do modelo de leitura. Configure alertas para o lag de projeção antes que seus usuários percebam dados obsoletos.
Automatize tarefas manuais. Mudanças manuais de esquema, reconstruções manuais de projeção e replays manuais de eventos são bombas-relógio. Crie scripts para sua estratégia de migração. Se você evoluir um esquema de evento, automatize o upcasting ou a transformação para que eventos antigos possam ser reprocessados pela nova lógica sem intervenção humana à meia-noite.
Documente suas escolhas. Escreva por que streams específicos existem, o que cada tipo de evento significa e quando a equipe deve escolher CRUD em vez de eventos. O event sourcing introduz carga cognitiva. Uma boa documentação evita que um novo engenheiro chute errado e faça o append de eventos malformados em um stream crítico.
Armadilhas que Desperdiçam Meses
O event sourcing tem uma maneira de parecer elegante em um diagrama e doloroso em produção. Fique atento a estas armadilhas.
Subestimar a complexidade. Reprocessar eventos para reconstruir o estado é conceitualmente simples. Gerenciar idempotência, snapshotting para performance e transações compensatórias entre agregados não é. Divida seu sistema em partes pequenas. Resolva um stream por vez.
Over-engineering. Não provisione um cluster Kafka de múltiplos nós apenas porque você imagina que seu volume de eventos um dia exigirá isso. O Postgres pode te levar surpreendentemente longe. Introduza nova infraestrutura apenas quando tiver um gargalo mensurável que não consiga resolver com sua configuração atual.
Ignorar dívida técnica. Esquemas de eventos antigos permanecem para sempre. Se você alterar o payload do OrderCreated, ainda terá dez milhões de eventos históricos no formato antigo. Monitore essa dívida. Planeje leitores retrocompatíveis ou scripts de migração. Não deixe o fardo de eventos legados atrasar cada nova funcionalidade.
Escolher ferramentas que a equipe não consegue operar. A melhor arquitetura falha se apenas uma pessoa a entende. Se sua equipe conhece Postgres e SQL, comece por aí. Se você introduzir um event store especializado, certifique-se de ter a expertise operacional para depurá-lo às duas da manhã.
Um Ponto de Partida Prático
Se esta abordagem se ajusta ao seu problema, não espere por uma reescrita de cinco trimestres. Comece esta semana.
Audite seus sistemas atuais. Encontre um lugar onde uma trilha de auditoria resolveria uma dor real. Talvez seja uma máquina de estados de pedidos que atualmente mantém uma única coluna status. Talvez seja um livro contábil onde correções de saldo exigem patches manuais no banco de dados. Escolha uma lacuna onde a sobrescrita de estado tenha te prejudicado.
Depois, escolha uma pequena melhoria que você possa fazer hoje. Crie uma tabela de eventos. Modele um stream. Escreva uma projeção que construa um modelo de leitura a partir desses eventos. Implemente-a atrás de uma feature flag. Observe-a lidar com tráfego real.
Event sourcing com PostgreSQL não é mágica. É uma ferramenta prática para equipes que precisam saber não apenas onde as coisas estão, mas como elas chegaram lá. Construa lentamente, meça honestamente e deixe que seus requisitos reais guiem a arquitetura.
