Posts · 8 November 2026 · 6 min read · 14 reads

Decoupled Consistency Between DynamoDB and Aurora PostgreSQL with CQRS and Event Sourcing

The logic of keeping the write load as an event stream in DynamoDB and projecting the read model into Aurora PostgreSQL, along with optimistic locking and error handling.

Putting both heavy writes and heavy reporting on a single table inevitably creates contention in the database. Write operations take row locks, and reports wait behind those locks. In this article I explain how combining the CQRS and Event Sourcing patterns can break this problem apart. On the write side we store events in DynamoDB, and on the read side we build a separate model on Aurora PostgreSQL. The target audience is backend and platform engineers who want to solve consistency and scaling problems in distributed systems in a real architecture.

Preparation

This setup requires Terraform 1.7 or later, version 5.40 of the AWS provider, a Python 3.12 environment, and the boto3, psycopg (version 3), and aws-lambda-powertools libraries. The IAM permissions needed for the direct integration between DynamoDB Streams and EventBridge Pipes should also be defined in advance. If this step is skipped, the part that wastes the most time is usually authorization errors.

DynamoDB as the Event Store

The core idea here is to add an immutable event such as "money deposited" instead of updating an account balance in place. We chose DynamoDB for the event store because it scales horizontally and supports conditional writes. We designed the table key as AggregateId (partition key) and Version (sort key). This way, all events belonging to the same entity are collected in the same physical partition, and it becomes possible to replay the state from the beginning.

We enable Streams on the table and publish only the new image (NEW_IMAGE). This way, the read side receives just enough data to process the newly added events.

Optimistic Locking and the Command Side

To prevent two operations from writing to the same entity at the same time, we use optimistic locking. The command computes the next version from the expected version and attempts the write. If the same version has already been written, the DynamoDB condition rejects it and the application interprets this as a conflict. A short example:

from botocore.exceptions import ClientError

def append_event(table, aggregate_id: str, version: int, event_type: str, payload: dict):
    try:
        table.put_item(
            Item={
                "AggregateId": aggregate_id,
                "Version": version,
                "EventType": event_type,
                "Payload": payload,
            },
            ConditionExpression="attribute_not_exists(Version)",
        )
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            raise RuntimeError("Çakışma: sürüm zaten var, durumu yeniden oku.")
        raise

On a conflict, the domain layer rebuilds the aggregate, re-evaluates the rule, and retries a limited number of times. With this approach we do not hold database rows locked for long, so the write flow does not choke even under high concurrency.

Projecting the Read Model

After events are written to DynamoDB, they flow through Streams to EventBridge Pipes and from there to a Lambda function that performs the projection. The pipe is filtered to pass only insert records. The Lambda decodes the events and updates the read table in Aurora PostgreSQL. Because the query API reads this table directly, clients do not need to know the internal structure of the event store.

The real gain of this architecture is on the read side. Reports, balances, and summaries come from a precomputed table, so there is no need to aggregate hundreds of events on every query. Even so, I recommend measuring expectations such as "sub-millisecond" in your own environment before accepting them; network latency and connection pooling can easily change that figure.

Out-of-Order Projections and Poison Batches

The most insidious problem in this architecture is that the order of events can be broken. Streams preserves the order within a partition, but retries or function scaling can change the order in which operations are processed. The conditional update used in the projection prevents the same event from being applied twice:

UPDATE account_read_model
SET balance = balance + $1, current_version = $2
WHERE account_id = $3 AND current_version < $2;

However, there is one point to be careful about here. If version 7 is processed first, then when version 6 arrives the condition is not satisfied, and the effect of event 6 is silently lost. So this check prevents duplicates, but it also drops late-arriving older events. In a real system, you either need to apply events in version order by waiting for the missing ones, or track the processed versions in a separate table and retry until the missing versions arrive.

The second common problem is that a single broken event causes Lambda to retry the same batch endlessly. In that case, the projection of the other records also stops. Defining a failure destination (an SQS-based dead-letter queue) on the Event Source Mapping and lowering the MaximumRetryAttempts value lets you move the problematic batch to the queue so the rest of the stream keeps flowing. The records in the queue can later be inspected and reprocessed.

Conclusion

Using CQRS and Event Sourcing together opens the way to scaling write and read loads independently of each other. DynamoDB stays elastic on the write side, while Aurora carries complex queries on the read side. This separation also improves resilience, because a slowdown on one side does not directly affect the other. Over time, the event store becomes a valuable data source. In later stages, you can project the same event stream into a graph database such as Neptune or a search engine such as OpenSearch to meet new analytical needs without slowing down the core system.

Highlights

  • Write and read models are physically separated; each scales on its own.
  • Because events are immutable, state history can be fully traced and rebuilt.
  • Optimistic locking ensures version consistency on the write side without row locks.
  • Projection does not produce correct balances unless out-of-order events are handled; version tracking is mandatory.
  • Do not go to production without defining a dead-letter queue for broken events.
  • The read model can be regenerated as needed, which makes new reports easier.

When to Use It

This pattern makes sense for systems with high write volume where read requirements differ significantly from the write model. Financial transactions, processes that require an audit trail, and areas that need multiple read representations benefit from this architecture. On the other hand, for simple CRUD applications, if the team lacks experience with event ordering and projection consistency, taking on the same complexity is usually an unnecessary cost. It is a healthier approach to measure the need first and only then apply this pattern.

References

  • Martin Fowler, "CQRS" (2011), martinfowler.com
  • Greg Young, "CQRS Documents" (2010), cqrs.nu
  • Martin Kleppmann, "Designing Data-Intensive Applications" (2017)

Read the original article on DEV Community ↗

Comments (0)

No comments yet; be the first.

Leave a comment

Comments are published after approval.