Course contentsShow
← System Design
Lesson 595 of 1,91916. Distributed TransactionsFree lesson

Semantic Lock Pattern

Using application-level flags to prevent concurrent access to saga-affected data and reduce isolation anomalies.

Semantic Lock Pattern

What You'll Learn

You'll learn how to use application-level flags to prevent concurrent access to saga-affected data, reducing isolation problems during long-running distributed transactions.

The Problem with Saga Isolation

In the previous lesson, you learned that sagas lack the isolation guarantees of traditional ACID transactions—multiple sagas can see and modify the same data concurrently, leading to anomalies like lost updates or dirty reads.

What is the Semantic Lock Pattern?

The Semantic Lock Pattern places an application-level flag or status field on data that a saga is currently processing. This flag acts as a "Do Not Touch" sign, warning other operations that this data is involved in an in-flight saga.

Unlike database-level locks (which are released when a local transaction commits), semantic locks remain set across the entire saga lifecycle—from the first step until the last step completes or all compensating transactions finish.

How It Works

Think of it like placing a "Reserved" sign on a restaurant table. Even though someone isn't sitting there right now, other customers know not to take it.

When your saga begins processing an order, you might set order.status = "PROCESSING". Other operations check this status before acting:

  • Another saga trying to cancel the same order sees "PROCESSING" and rejects the cancellation
  • A query for completed orders excludes "PROCESSING" orders
  • The lock is removed only when the saga finishes (success) or fully compensates (failure)

The Trade-off

This pattern reduces isolation anomalies but decreases concurrency—legitimate operations might be blocked waiting for saga completion. You're trading correctness for availability on a per-entity basis.

Key Takeaway: Semantic locks use application-managed flags to mark data involved in active sagas, preventing concurrent access and reducing isolation anomalies at the cost of decreased concurrency.