Skip to content

How to implement Last-Write-Wins Conflict Resolution in bidirectional CDC with AWS DMS and Aurora PostgreSQL?

0

The Problem

In bidirectional CDC pipelines between legacy mainframe systems and AWS Aurora PostgreSQL, the same record can be updated on both sides within milliseconds of each other. AWS DMS has no native mechanism to determine which update should win — resulting in either data corruption, infinite replication loops, or both.

This is especially critical during live migration phases where legacy and cloud systems must coexist and stay in sync simultaneously.

Root Cause

DMS replicates changes as they arrive without timestamp comparison. When System A updates a record and System B updates the same record before the first change propagates, DMS applies both blindly — leaving the final state determined by network latency rather than business intent.

Solution — Last-Write-Wins Conflict Resolution Pattern

I developed and validated this pattern as part of the Live Data Coexistence Framework (LDCF) for zero-downtime enterprise MIS modernization:

Add a last_modified_ts column (microsecond precision) to every replicated table on both sides Implement an Aurora PostgreSQL trigger that compares incoming last_modified_ts against the existing row before applying the update If incoming timestamp is older than stored timestamp → reject the update silently and log to audit table If the incoming timestamp is newer → apply the update and propagate forward Use DMS transformation rules to preserve and forward the source timestamp through the pipeline

Production Results

Validated across 300+ tables, 1M+ DML transactions, bidirectional sync between DB2 z/OS and Aurora PostgreSQL — failure rate below 0.1% and zero unrecovered data loss.

Full framework and pattern documentation: Zenodo: https://zenodo.org/records/21313169

Has anyone implemented similar conflict resolution strategies in AWS DMS? Would love to hear alternative approaches and edge cases others have encountered.

4 Answers
1
Accepted Answer

Timestamp-based LWW with a guard trigger is a common, sound baseline for coexistence migrations. Here are the edge cases that usually break it, plus a few alternatives. Your Zenodo record's abstract mentions that LDCF uses a Kafka-based reverse path for cloud-to-legacy sync, so some of the DMS-specific points below may only apply to the DB2 → Aurora direction.

Edge cases to check

  1. Clock skew between z/OS and Aurora. Microsecond precision doesn't help if the two clocks differ by milliseconds. Within the skew window, the system with the faster clock always wins, whatever the real order. Options:

    • Measure and bound the skew, and alert when it's exceeded.
    • Use a hybrid logical clock, so a node never issues a timestamp lower than one it has already seen.
    • At minimum, store timestamps in UTC everywhere. z/OS TOD versus local time and DST changes are classic sources of bugs.
  2. Ties. Two sides can produce the same timestamp. Add a deterministic tiebreaker, such as an origin_id column compared after the timestamp, so both sides converge on the same winner.

  3. Triggers and session_replication_role. Many DMS PostgreSQL targets set session_replication_role = replica through afterConnectScript to suppress triggers and FK checks during apply. When that's set, ordinary triggers don't fire, and your LWW guard is silently bypassed. Declare the guard with ALTER TABLE ... ENABLE ALWAYS TRIGGER, or confirm the endpoint doesn't set the role.

  4. Who writes last_modified_ts. Only the originating write should set it. If a local trigger also stamps now() on replicated applies, every apply looks like a new write, and you've rebuilt the loop you were trying to prevent. The trigger has to distinguish local writes from replicated ones, by session role, application user, or an origin column.

  5. Loop prevention is a separate problem from conflict resolution. DMS has task-level loopback prevention settings for bidirectional replication. Using them, or filtering on an origin column, stops echo loops independently of LWW. DMS doesn't provide conflict resolution, so that remains your responsibility.

  6. Deletes. With plain LWW, a delete racing a concurrent update can resurrect the row or lose the delete, depending on arrival order. Soft deletes, or tombstones carrying a timestamp, make deletes take part in the same comparison.

  7. Insert/insert conflicts. Both sides creating the same natural key isn't an update conflict. It hits DMS apply error handling. Decide in advance whether that's an upsert, an error to log, or impossible by design, for example with key ranges assigned per side.

  8. LOB columns. In limited or full LOB mode, DMS can write the row and then update the LOB in a separate statement. That second statement carries the same timestamp, so a strict > comparison can reject your own follow-up write. Allow equal timestamps from the same origin.

  9. Batch apply. With BatchApplyEnabled, DMS applies net changes in bulk. Test the trigger under that mode separately, because changes can be applied in a different shape than they were captured.

  10. Row-level LWW loses concurrent field edits. If one side updates a premium and the other updates an address within the window, one change disappears entirely. For insurance data, that's often not acceptable business behavior, even if replication is "correct."

Alternatives worth comparing

  • Single writer per entity, or per table, during coexistence. This is often the most robust option. Route each entity's writes to one system at a time, and flip ownership as each table migrates. It fits naturally with your table lifecycle mechanism. Conflicts become impossible instead of resolved.
  • Column-level or field-group merge, using a timestamp per field group instead of per row, for tables where concurrent edits to different fields are expected.
  • Version counters with a conflict queue. Detect conflicts with an optimistic version column. Auto-resolve the safe ones and send the rest to a review table, rather than dropping them silently. Silent rejection plus a 24-hour reconciliation window is fine for some data. For financial fields, routing to a review queue is usually safer.
  • pgactive (active-active replication for Aurora and RDS PostgreSQL) has built-in LWW. It only works between PostgreSQL nodes, so it won't help with DB2, but it's a useful reference for how origin tracking and tiebreaking are handled.

It would help readers if you shared how LDCF handles skew between the DB2 and Aurora clocks, and whether the sub-0.1% failure rate includes conflicts that were rejected or only pipeline errors.

EXPERT

answered a month ago

  • Thank you; this is exactly the kind of rigorous analysis the pattern needed. Let me address each point from our production implementation: Clock skew: You're correct that microsecond precision alone doesn't solve skew. We synchronize both z/OS and Aurora to NTP with a monitored drift threshold and alert on deviation. UTC storage is enforced throughout. Hybrid logical clocks are not currently implemented - a valid gap worth noting.

    Ties/tiebreaker: In our implementation, LEGACY wins on ties by design during the coexistence phase since the mainframe is the system of record until full cutover. A deterministic tiebreaker via origin identity is a good hardening recommendation I'll document. session_replication_role: In our implementation, the LWW timestamp comparison is embedded within the upsert statement itself (INSERT ON CONFLICT DO UPDATE SET ... WHERE excluded.last_modified > target.last_modified) rather than as a separate trigger. This sidesteps the session_replication_role bypass issue entirely since upsert is a SQL statement, not a trigger. For implementations using a trigger-based guard instead, your point about ALTER TABLE ... ENABLE ALWAYS TRIGGER is critical and should be an explicit implementation requirement.

  • Who writes LAST_MODIFIED: Pattern 3 reuses the existing LAST_MODIFIED column already present on all legacy mainframe tables — no new column is added, which matters when working with production mainframe tables already under operational load. All target write operations use PostgreSQL upsert semantics via INSERT ON CONFLICT DO UPDATE, applying the incoming event only when the incoming LAST_MODIFIED is newer than the stored value. The DataSyncFlag (set by Pattern 2 -> Origin-Aware Circular Replication Guard) identifies cloud-originated replicated writes and excludes them from triggering a new timestamp, preventing the loop where replicated applies stamp now(). Loop prevention: Handled separately by Pattern 2 (Origin-Aware Circular Replication Guard) via DataSyncFlag filtering — independent of conflict resolution as you correctly noted.

    Deletes: We use soft deletes during the coexistence phase - hard deletes are not permitted, which avoids the race condition between a delete and a concurrent update you described.

    Insert/insert conflicts: Structurally prevented by Pattern 1 (Dual-Sequence Key Partitioning) - legacy uses even sequences, cloud uses odd sequences, making primary key collisions impossible by design rather than resolved at runtime.

  • LOB columns and BatchApply: Genuine gaps not covered in the current paper. I'll add these as known limitations in the next revision. Row-level vs field-level LWW: Acknowledged. For our insurance domain, premium and address fields are on separate tables by design, which reduces but doesn't eliminate this risk. Field-group merge is the correct long-term solution for tables where concurrent field edits to different columns are expected.

    On your clarifying question: The sub-0.1% failure rate refers to pipeline errors requiring manual intervention — events that failed all three SQS retry attempts and landed in the Dead Letter Queue. Rejected conflicts are logged to the audit table and fall within the 24-hour bounded drift reconciliation window (Pattern 8 - Eventual Consistency with Bounded Drift). I'll clarify this distinction explicitly in the paper.

    This is exactly the peer review that strengthens a pattern from a working solution to a documented standard. Thank you - I'll incorporate these points into the next revision of the Zenodo paper.

1

Thanks for the detailed follow-up. The upsert approach and the even/odd key partitioning are cleaner than what I assumed. A few things your answers raise that might be worth checking before the next revision:

  1. The tie rule and the SQL disagree. WHERE excluded.last_modified > target.last_modified means that on an exact tie, the stored row wins, whichever side it came from. If legacy is meant to win ties, the predicate has to encode that, for example:

    WHERE excluded.last_modified > target.last_modified
       OR (excluded.last_modified = target.last_modified AND excluded.origin = 'LEGACY')

    This needs mirroring on the DB2 side as well, or the two systems can resolve the same tie differently and diverge.

  2. How LAST_MODIFIED is maintained on DB2. If it's a ROW CHANGE TIMESTAMP generated column, or set by a DB2 trigger, then DB2 itself re-stamps it when your reverse path writes cloud changes into DB2. DataSyncFlag can't stop that, so the cloud's timestamp is replaced by apply time, and LWW ordering breaks for those rows. If instead the application maintains the column, look for legacy batch jobs or utilities that update rows without touching it. Those changes would carry stale timestamps and lose conflicts they should win.

  3. Ordering with SQS. With standard queues and DLQ redrive, events can arrive out of order or much later. The LWW guard handles that correctly for updates, as long as soft-delete events carry LAST_MODIFIED and go through the same guarded upsert. Otherwise an old update replayed from the DLQ could revive a soft-deleted row.

  4. Even/odd sequences only cover surrogate keys. Business keys with unique constraints, such as policy or claim numbers, can still collide if both sides can create them. That's worth a sentence in the paper.

  5. Document the skew bound as the correctness window. With NTP plus a drift alert, the effective guarantee is that LWW reflects real order for writes more than X ms apart, where X is your alert threshold. Stating that number makes the guarantee concrete.

  6. Scope of the DMS-specific caveats. Since the apply path is a custom upsert consumer fed through SQS, rather than DMS writing straight to the target, the batch apply and LOB caveats may only apply if DMS's native apply is used anywhere in the pipeline. Saying which path each pattern covers will save readers from misapplying them.

Good luck with the revision.

EXPERT

answered a month ago

  • Thank you so much; your input is really helpful. Point 1 (Tie rule): You are correct - excluded.last_modified > target.last_modified silently drops the incoming row on exact ties. In our domain, millisecond-precision NTP-synchronized timestamps make true ties rare, but the behavior should be explicit. The paper will document the tie-breaking variant: add OR (excluded.last_modified = target.last_modified AND excluded.origin = 'LEGACY') to establish legacy as the explicit tie-winner on the forward path.

    Point 2 (DB2 LAST_MODIFIED stamping): Pattern 3 uses a two-layer guard, not timestamp alone. The upstream listener first checks DataSyncFlag: if DataSyncFlag = 'CLOUD', the event is skipped immediately (Pattern 2 — circular replication guard) before LAST_MODIFIED is ever evaluated. LAST_MODIFIED is only compared when DataSyncFlag is NULL or ‘LEGACY’, meaning the event is confirmed legacy-originated. Since DB2 ROW CHANGE TIMESTAMP is authoritative and set by DB2 on every write, reverse-path writes (cloud→legacy) carry an accurate DB2 timestamp — but Pattern 2 already discards them before Pattern 3 runs. The two patterns compose: DataSyncFlag eliminates circular events; LAST_MODIFIED arbitrates between competing legitimate updates. The paper will add a note making this composition explicit.

  • Point 3 (SQS DLQ ordering): The pipeline applies CDC operations faithfully as received from the source system — INSERT, UPDATE, and DELETE are all executed as-is. DataSyncFlag and LAST_MODIFIED govern UPDATE conflict resolution only. For DELETEs, the source system CDC event is the authority; there are no soft deletes in this implementation. DLQ redrive replays the original CDC event, and since DELETEs are idempotent at the database level (deleting an already-deleted or non-existent row is a no-op), redelivery does not create incorrect state. The paper will add a note clarifying that LWW timestamp comparison applies to UPDATE operations only, and that DELETE operations are applied directly as source-authoritative events.

    Point 4 (Business key scope): Pattern 1 (Dual-Sequence Key Partitioning) partitions surrogate primary keys only — legacy sequences generate even values, cloud sequences generate odd values. Business identifiers such as policy numbers and claim numbers are assigned exclusively by legacy systems during the coexistence period. Cloud microservices reference these as foreign identifiers and never generate new values for existing legacy entities. No collision is possible because write authority over business key generation belongs to one system. The paper will add a clarifying note distinguishing surrogate key collision (solved by Pattern 1) from business key authority (enforced by coexistence governance)

  • Point 5 (Clock skew bound): The framework addresses clock skew through two complementary mechanisms. First, Pattern 5 (Three-Tier DLQ) provides operational safety: any event failing processing is automatically retried three times via SQS, then written to DynamoDB with PERMANENT_FAILED status and 180-day TTL for manual reconciliation and reprocessing. Second, Pattern 8 (Eventual Consistency with Bounded Drift) runs a daily AWS Glue reconciliation job that detects any data mismatch including timestamp divergence, with a hard 24-hour upper bound on undetected drift. Together these provide real-time retry resilience and bounded detection of any divergence LWW may have mishandled. The paper will document this composition explicitly as the correctness guarantee. Point 6 (DMS scope): DMS in our architecture is scoped exclusively to CDC capture - it reads DB2 change events with transaction preservation enabled (BatchApplyPreserveTransaction: true), delivering records as ordered CSV files to S3 in database commit order. DMS never applies writes to any target. All write logic — LWW conflict resolution (Pattern 3), out-of-order tolerance (Pattern 4), and DLQ handling (Pattern 5) — executes in the custom Spring Boot upstream listener. The session_replication_role bypass concern applies only to DMS native apply mode, which is not used here. The paper will add a scope note clarifying DMS’s capture-only role and that all integrity patterns operate in the consumer layer. Thank you much again

1

AWS DMS supports bidirectional replication for PostgreSQL/Aurora PostgreSQL, but it does not provide a general-purpose last-write-wins conflict-resolution mechanism for two systems independently modifying the same record. DMS's bidirectional configuration primarily addresses replication in both directions and loopback prevention. AWS specifically recommends configuring loopback prevention so that a change replicated from A → B isn't immediately replicated back from B → A. If both systems can independently modify the same row, a last-write-wins strategy therefore needs to be implemented at the application/database level. Using a source-generated last_modified_ts can be a reasonable approach, but I would be careful about relying on database-side triggers alone. You also need to consider:

  • Clock synchronization between the two systems
  • Timestamp precision
  • Inserts versus updates
  • Deletes/tombstones
  • Transaction ordering
  • Replication latency
  • Loopback prevention
  • What happens when timestamps are identical I would also recommend defining what "last write" actually means. Wall-clock timestamp is not necessarily the same thing as transaction/commit ordering. For high-value data, an explicit conflict-resolution mechanism with deterministic conflict logging may be safer than silently discarding an older update.

answered a month ago

  • Thank you — these are precisely the right considerations. Our implementation addresses each: (1) Loopback prevention — Pattern 2 (Origin-Aware Circular Replication Guard) uses a DataSyncFlag column on all legacy tables. The Kafka listener sets DataSyncFlag='CLOUD' on every reverse-path write; the upstream CDC listener skips any record where DataSyncFlag='CLOUD' before applying it, preventing circular replication without relying on DMS bidirectional configuration. (2) Clock synchronization and precision — NTP-synchronized hosts; Pattern 8 (Eventual Consistency with Bounded Drift) runs a daily AWS Glue reconciliation job with a hard 24-hour upper bound on undetected drift. (3) Inserts vs updates — Pattern 4 (Upsert Tolerance for Out-of-Order Events) uses INSERT ON CONFLICT DO UPDATE so any operation regardless of arrival order produces a valid state. (4) Deletes — CDC DELETE events from the source system are applied directly as authoritative operations; no tombstone mechanism needed. (5) Timestamp ties — stored row wins on exact ties (legacy is system of record during coexistence); paper will document this explicitly. (6) Conflict logging — Pattern 5 (Three-Tier DLQ) audits every DML event to DynamoDB with SUCCESS/FAILED/PERMANENT_FAILED status and 180-day retention. No update is silently discarded without an audit trail. Full architecture: https://doi.org/10.5281/zenodo.21313169

0

AWS DMS does not natively provide last-write-wins conflict resolution for bidirectional replication scenarios. However, there are several AWS-native approaches you can consider that align with your requirements:

PostgreSQL Active-Active Replication with pgactive Extension

For Aurora PostgreSQL environments, the pgactive extension provides built-in conflict detection and automatic resolution using timestamp-based logic. It tracks commit timestamps on both database instances and automatically applies changes with the latest timestamp when conflicts occur. The extension logs all conflicts in the pgactive.pgactive_conflict_history table for audit purposes. This approach works per database and allows each instance to accept data changes from any source, with asynchronous replication handling conflict resolution automatically.

Aurora DSQL for Distributed Transactions

For scenarios requiring strong consistency across regions, Aurora DSQL uses optimistic concurrency control (OCC) with snapshot isolation. Transactions execute locally without holding locks, and conflict detection occurs only at commit time. When two transactions modify the same row, the transaction with the earliest commit time succeeds, while the conflicting transaction receives a serialization error that applications can retry. This eliminates lock contention while maintaining ACID compliance.

DMS Data Resync for Consistency Management

AWS DMS version 3.6.1 introduced Data Resync functionality that automatically detects and resolves data inconsistencies during migrations. It identifies discrepancies through data validation between source and target databases and addresses them by retrieving current values from the source. While not specifically designed for bidirectional conflict resolution, it can help maintain consistency during migration phases by tracking validation failures in the awsdms_validation_failures_v2 table.

Implementation Considerations

For bidirectional CDC scenarios, the key challenge is that DMS applies changes as they arrive without native timestamp comparison. Your trigger-based approach with microsecond-precision timestamps is a valid pattern. When implementing similar solutions:

  • Ensure timestamp precision is sufficient to handle near-simultaneous updates
  • Implement comprehensive audit logging for rejected updates
  • Design retry logic for serialization failures
  • Consider idempotent transaction design to enable safe retries
  • Monitor for high contention on single keys or small key ranges

For production deployments, minimize contention by spreading updates across your key range through appropriate schema design, such as using random primary keys rather than sequential ones. This reduces the likelihood of conflicts on the same records.

The choice between these approaches depends on your specific requirements: pgactive for PostgreSQL-to-PostgreSQL active-active replication, Aurora DSQL for multi-region strong consistency, or custom trigger-based logic when working with heterogeneous sources like DB2 z/OS where AWS-native solutions may not directly apply.
Sources
Handling conflicts in active-active replication - Amazon Relational Database Service
Amazon Aurora DSQL for global-scale financial transactions | AWS Database Blog
Concurrency control in Aurora DSQL - Amazon Aurora DSQL
Data consistency with AWS DMS data resync | AWS Database Blog

answered a month ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.