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.
Prueba todo. Realiza pruebas unitarias de tus manejadores de eventos. Realiza pruebas de integración en la ruta de anexado (append path). Lo más importante: prueba los escenarios de fallo. ¿Qué sucede cuando dos nodos anexan a la misma transmisión (stream) simultáneamente? ¿Qué sucede cuando un trabajador de proyección falla a mitad de un lote (batch)? Escribe pruebas que verifiquen tu concurrencia optimista y tus garantías de entrega de al menos una vez (at-least-once delivery).
Monitorea en producción. La tabla de eventos crecerá. A diferencia de un esquema normalizado donde las actualizaciones mantienen constantes el número de filas, el event sourcing es intencionadamente aditivo. Rastrea el tamaño de la tabla, la E/S de disco y el retraso (lag) entre tu modelo de escritura y tus proyecciones del modelo de lectura. Configura alertas sobre el retraso de la proyección antes de que tus usuarios noten datos desactualizados.
Automatiza las tareas manuales. Los cambios manuales de esquema, las reconstrucciones manuales de proyecciones y la repetición manual de eventos son bombas de tiempo. Automatiza tu estrategia de migración mediante scripts. Si evolucionas un esquema de eventos, automatiza el upcasting o la transformación para que los eventos antiguos puedan ser procesados con la nueva lógica sin intervención humana a medianoche.
Documenta tus decisiones. Escribe por qué existen flujos (streams) específicos, qué significa cada tipo de evento y cuándo el equipo debería elegir CRUD en lugar de eventos. El event sourcing introduce una carga cognitiva. Una buena documentación evita que un nuevo ingeniero adivine incorrectamente y anexe eventos malformados a un flujo crítico.
Trampas que desperdician meses
El event sourcing tiene la capacidad de sonar elegante en un diagrama y doloroso en producción. Ten cuidado con estas trampas.
Subestimar la complejidad. Repetir eventos para reconstruir el estado es conceptualmente sencillo. Gestionar la idempotencia, el snapshotting para el rendimiento y las transacciones compensatorias entre agregados no lo es. Divide tu sistema en piezas pequeñas. Resuelve un stream a la vez.
Sobreingeniería. No aprovisiones un clúster de Kafka de múltiples nodos solo porque imaginas que tu volumen de eventos lo requerirá algún día. Postgres puede llevarte sorprendentemente lejos. Introduce nueva infraestructura solo cuando tengas un cuello de botella medido que no puedas solucionar con tu configuración actual.
Ignorar la deuda técnica. Los esquemas de eventos antiguos perduran para siempre. Si cambias el payload de OrderCreated, seguirás teniendo diez millones de eventos históricos con la forma antigua. Rastrea esta deuda. Planifica lectores compatibles con versiones anteriores o scripts de migración. No permitas que la carga de los eventos heredados ralentice cada nueva funcionalidad.
Elegir herramientas que el equipo no puede operar. La mejor arquitectura falla si solo una persona la entiende. Si tu equipo conoce Postgres y SQL, empieza por ahí. Si introduces un almacén de eventos especializado, asegúrate de tener la experiencia operativa para depurarlo a las dos de la mañana.
Un punto de partida práctico
Si este enfoque se adapta a tu problema, no esperes a una reescritura de cinco trimestres. Empieza esta semana.
Audita tus sistemas actuales. Busca un lugar donde un registro de auditoría (audit trail) resolvería un problema real. Tal vez sea una máquina de estados de pedidos que actualmente mantiene una única columna status. Quizás sea un libro contable financiero donde las correcciones de saldo requieren parches manuales en la base de datos. Elige una brecha donde la sobrescritura de estados te haya causado problemas.
Luego, elige una pequeña mejora que puedas realizar hoy. Crea una tabla de eventos. Modela un stream. Escribe una proyección que construya un modelo de lectura a partir de esos eventos. Despliégala tras una feature flag. Observa cómo gestiona el tráfico real.
El event sourcing con PostgreSQL no es magia. Es una herramienta práctica para equipos que necesitan saber no solo dónde están las cosas, sino cómo llegaron allí. Construye lentamente, mide con honestidad y deja que tus requisitos reales guíen la arquitectura.
