When an application runs on multiple servers, some operations must be performed by only one worker at a time. Daily settlement, stock reservation, invoice generation, and order processing are common examples. An in-memory lock is not sufficient because each application server has its own memory and cannot coordinate with another instance.
SQL Server provides sp_getapplock for this purpose. An application lock is placed on a logical resource name chosen by the developer rather than on a specific table row. Multiple application instances can therefore use the same database as a shared coordination point.
When should you use an application lock?
Application locks are useful when:
- Only one background worker should execute a particular job at a time
- A customer, order, or account must be processed by one workflow at a time
- Inventory, quota, or sequence updates contain a critical section
- Several application servers must coordinate access to a logical resource
This mechanism does not replace database constraints. Unique indexes, foreign keys, validation rules, and appropriate transaction boundaries are still required. The application lock controls concurrency at the workflow level; it is an additional coordination layer, not a substitute for data integrity.
A practical failure: two workers process one order
Imagine an e-commerce system receiving payment events through a queue. Because of network retries, the same OrderId can be delivered to two workers at nearly the same time. If both workers read the order as Paid, they may both reduce inventory or create shipment records.
This pattern is unsafe on its own:
IF EXISTS (SELECT 1 FROM dbo.OrderProcessing WHERE OrderId = @OrderId)
RETURN;
INSERT INTO dbo.OrderProcessing(OrderId, ProcessedAt)
VALUES (@OrderId, SYSUTCDATETIME());Both sessions may pass the IF EXISTS check before either insert becomes visible. That is a race condition. A unique index can reject the second insert, but it does not necessarily protect the entire business workflow. The second worker might already have performed another side effect while the first worker is updating inventory.
Design a stable resource name
An application lock is identified by a resource string and is scoped to the current database. All code paths that need the same logical lock must generate exactly the same name. Resource names are binary-compared and therefore case-sensitive, so Order:10025 and order:10025 are different resources.
Use names that make the scope explicit:
Order:10025locks only order 10025.Job:DailySettlementprevents overlapping settlement jobs.Customer:42:Balancecoordinates balance changes for one customer.
A resource string can contain up to 255 characters. Only the first 32 characters are available in plain text when the lock is inspected, so avoid putting the most important diagnostic information at the end of a very long name.
A transaction-owned implementation
For workflows that update data, @LockOwner = 'Transaction' is usually the safest starting point. The lock is released automatically when the transaction commits or rolls back. This reduces the risk of leaving a session-owned lock behind accidentally.
The following procedure prevents concurrent processing of the same order:
CREATE OR ALTER PROCEDURE dbo.ProcessOrder
@OrderId bigint
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @LockResult int;
DECLARE @Resource nvarchar(255) = CONCAT(N'Order:', @OrderId);
BEGIN TRANSACTION;
EXEC @LockResult = sys.sp_getapplock
@Resource = @Resource,
@LockMode = 'Exclusive',
@LockOwner = 'Transaction',
@LockTimeout = 3000;
IF @LockResult < 0
BEGIN
ROLLBACK TRANSACTION;
THROW 51001, 'Order lock could not be acquired.', 1;
END;
IF EXISTS
(
SELECT 1
FROM dbo.OrderProcessing
WHERE OrderId = @OrderId
)
BEGIN
COMMIT TRANSACTION;
RETURN;
END;
UPDATE dbo.Orders
SET Status = 'Processed',
ProcessedAt = SYSUTCDATETIME()
WHERE Id = @OrderId
AND Status = 'Paid';
INSERT INTO dbo.OrderProcessing(OrderId, ProcessedAt)
VALUES (@OrderId, SYSUTCDATETIME());
COMMIT TRANSACTION;
END;Two protections work together here. The application lock serializes concurrent workflows for the same order. A unique index on OrderProcessing.OrderId provides a second line of defense if an unexpected code path attempts to create a duplicate record.
Always inspect the return code
sp_getapplock reports many failures through a return code instead of raising an exception. A return value of zero means the lock was granted immediately. A value of one means it was granted after waiting. Negative values indicate failure: -1 is a timeout, -2 is cancellation, -3 means the request was selected as a deadlock victim, and -999 indicates parameter validation or another call error.
Do not assume that a deadlock involving an application lock automatically rolls back the transaction. The required rollback or alternative action must be handled explicitly. Every call should therefore check the return value before continuing with business changes.
When is session ownership appropriate?
With @LockOwner = 'Session', the lock remains associated with the connection until it is explicitly released or the session ends. This can be useful for a connection-scoped mutex, but it requires disciplined cleanup.
Session ownership is especially risky with connection pooling. Returning a connection to the pool does not necessarily destroy the underlying SQL Server session. If the code forgets to call sys.sp_releaseapplock, a later request may reuse the connection while the logical lock is still held.
If session ownership is necessary, release the lock on every successful path and every error path. For ordinary web requests and data-changing workflows, transaction ownership is usually easier to reason about.
Set a deliberate wait policy
The default wait behavior may be unsuitable for a web request. A request that waits for minutes can exhaust application threads and connection-pool capacity. For a job that can be retried later, use a bounded timeout such as @LockTimeout = 0 to fail fast when the resource is busy, or use a short timeout followed by a controlled retry.
Retries should be limited and observable. Avoid an infinite loop that retries every few milliseconds. A maximum attempt count, backoff delay, and structured log entry containing the resource name and timeout result make the behavior safer in production.
Inspect application locks
Application locks can be viewed through sys.dm_tran_locks using the APPLICATION resource type:
SELECT
request_session_id,
request_status,
request_mode,
request_owner_type,
resource_description
FROM sys.dm_tran_locks
WHERE resource_type = 'APPLICATION';Review the session ID, resource description, owner type, and request status together. The presence of a lock is not automatically a problem. The important questions are how long it has been held, which workflow owns it, and whether other requests are waiting.
Production checklist
- Generate resource names consistently in every service and code path.
- Keep the lock scope as narrow as the business rule allows.
- Prefer transaction-owned locks for data-changing workflows.
- Handle every return code explicitly.
- Define timeout and retry behavior before deployment.
- Keep unique indexes and other integrity constraints in place.
- Log acquisition time, wait duration, timeout results, and resource names.
- Test session-owned locks carefully when connection pooling is enabled.
SQL Server application locks turn the database into a simple coordination service for distributed applications. With stable resource naming, short transactions, bounded waits, explicit error handling, and proper constraints, duplicate jobs and race conditions become controlled engineering problems instead of intermittent production surprises.
0 Comments