sp_getapplock)SQL Server Application Locks are a native database feature that allows developers to create and manage logical locks on user-defined resources.
Unlike traditional database locks, which protect database structures such as rows, pages, indexes and tables, application locks protect developer-defined resources identified by a name.
These resources do not need to correspond to any existing database object.
For example:
@Resource = 'DAILY_ETL_PROCESS'
SQL Server does not require a table, procedure or other database object named DAILY_ETL_PROCESS.
The resource name represents a logical operation that developers want to protect against conflicting concurrent execution.
Application locks are:
Explicitly requested by developers.
Managed by the SQL Server Lock Manager.
Independent of physical database objects.
Compatible with transaction-level and session-level ownership.
Configurable through different lock modes and timeout settings.
Integrated with SQL Server deadlock detection.
Traditional database locks protect data during database operations.
However, sometimes developers need to protect an entire business process rather than individual database objects.
For example, two sessions may attempt to execute the same ETL process simultaneously.
SESSION 1 SESSION 2
| |
v v
Execute ETL Execute ETL
| |
+------------+------------+
|
v
Concurrent execution
Potential data conflicts
Without additional concurrency control, simultaneous execution may cause duplicate data, inconsistent calculations, conflicting operations or unnecessary resource consumption.
SESSION 1 SESSION 2
| |
v v
Request lock Request lock
| |
+------------+------------+
|
SQL Server Lock
Manager
|
+------------+------------+
| |
Lock granted Lock not granted
| |
Execute ETL Wait or skip
Application locks allow developers to prevent these situations without creating additional control tables or maintaining execution flags.
|
Characteristic |
Traditional locks |
Application locks |
|---|---|---|
|
Protected resource |
Database objects and data |
User-defined resource |
|
Acquisition |
Usually automatic |
Explicit |
|
Managed by |
SQL Server Lock Manager |
SQL Server Lock Manager |
|
Requires existing database object |
Generally yes |
No |
|
Protects business processes |
Indirectly |
Directly |
|
Transaction-level ownership |
Yes |
Yes |
|
Session-level ownership |
Generally no |
Yes |
|
Deadlock detection |
Yes |
Yes |
Application locks do not replace traditional database locks.
They provide an additional layer of concurrency control at the application or business-process level.
SQL Server provides two main system stored procedures for managing application locks.
|
Procedure |
Description |
|---|---|
|
|
Acquires an application lock |
|
|
Releases an application lock |
Additionally, SQL Server provides functions for checking application lock information.
|
Function |
Description |
|---|---|
|
|
Returns the current lock mode |
|
|
Checks whether a requested lock can be granted |
These functions allow developers to inspect application locks without acquiring a new lock.
DECLARE @ReturnCode INT;
EXEC @ReturnCode = sp_getapplock
@Resource = 'Resource_Name',
@LockMode = 'Exclusive',
@LockOwner = 'Transaction',
@LockTimeout = 5000,
@DbPrincipal = 'public';
|
Parameter |
Description |
|---|---|
|
|
User-defined resource name |
|
|
Requested lock mode |
|
|
Transaction or session ownership |
|
|
Maximum waiting time in milliseconds |
|
|
Database principal associated with the lock |
The default lock owner is Transaction. Therefore, an active transaction must exist when using the default ownership type.
The default database principal is public.
The @Resource parameter identifies the logical resource that must be protected.
Examples of resource names:
'DAILY_ETL_PROCESS'
'MONTHLY_DATA_RELOAD'
'CUSTOMER_BALANCE_CALCULATION'
'INVOICE_GENERATION'
'DATA_MIGRATION'
Resource names are case-sensitive, regardless of the database collation, and support up to 255 characters.
SQL Server internally identifies an application lock using a combination of:
Current database ID.
Database principal.
Resource name.
Consequently, application locks with identical names in different databases are independent.
DATABASE_A DATABASE_B
+----------------------+ +----------------------+
| DAILY_ETL_PROCESS | | DAILY_ETL_PROCESS |
| Exclusive lock | | Exclusive lock |
| GRANTED | | GRANTED |
+----------------------+ +----------------------+
No conflict
Both databases can independently acquire an exclusive lock on the same resource name.
Similarly, different database principals can represent independent application lock resources even within the same database.
SQL Server supports five application lock modes.
|
Lock mode |
Description |
|---|---|
|
|
Allows multiple compatible shared locks |
|
|
Allows shared access while preventing another update lock |
|
|
Prevents other owners from acquiring conflicting locks |
|
|
Represents shared-lock intent |
|
|
Represents exclusive-lock intent |
|
Existing / Requested |
IS |
IX |
S |
U |
X |
|---|---|---|---|---|---|
|
IS |
✔ |
✔ |
✔ |
✔ |
✖ |
|
IX |
✔ |
✔ |
✖ |
✖ |
✖ |
|
S |
✔ |
✖ |
✔ |
✔ |
✖ |
|
U |
✔ |
✖ |
✔ |
✖ |
✖ |
|
X |
✖ |
✖ |
✖ |
✖ |
✖ |
Abbreviations: IS — IntentShared, IX — IntentExclusive, S — Shared, U — Update, X — Exclusive.
For preventing simultaneous execution of stored procedures or ETL processes, Exclusive is generally the most appropriate lock mode.
SQL Server supports two types of application lock ownership.
@LockOwner = 'Transaction'
The application lock belongs to the current transaction.
An active transaction must exist before requesting the lock.
BEGIN TRANSACTION;
The lock is automatically released when the owning transaction ends through a full COMMIT or ROLLBACK.
BEGIN TRANSACTION
|
v
Acquire application lock
|
v
Execute business logic
|
v
COMMIT / ROLLBACK
|
v
Automatic lock release
Transaction-level locks are useful when the protected operation must be executed as a single transaction.
@LockOwner = 'Session'
The application lock belongs to the database session rather than a specific transaction.
An active transaction is not required.
The lock remains active even after executing COMMIT or ROLLBACK.
It is released when explicitly requested using sp_releaseapplock or when the owning session terminates.
Acquire application lock
|
v
BEGIN TRANSACTION
Execute Step 1
COMMIT
|
| Application lock remains active
v
BEGIN TRANSACTION
Execute Step 2
COMMIT
|
| Application lock remains active
v
sp_releaseapplock
|
v
Lock released
Session-level locks are particularly useful for long-running ETL processes that execute multiple transactions and intermediate commits.
|
Characteristic |
Transaction |
Session |
|---|---|---|
|
Active transaction required |
Yes |
No |
|
Released after COMMIT |
Yes, when transaction ends |
No |
|
Released after ROLLBACK |
Yes, when transaction ends |
No |
|
Explicit release supported |
Yes |
Yes |
|
Can protect multiple transactions |
No |
Yes |
|
Suitable for multi-stage ETL |
Limited |
Yes |
The @LockTimeout parameter determines how long SQL Server waits when a requested application lock cannot be granted immediately.
The value is specified in milliseconds.
|
Value |
Behavior |
|---|---|
|
|
Return immediately if unavailable |
|
|
Wait up to 1 second |
|
|
Wait up to 5 seconds |
|
|
Wait up to 1 minute |
|
|
Wait indefinitely, unless interrupted |
If the parameter is omitted, SQL Server uses the current @@LOCK_TIMEOUT setting.
For scheduled jobs and ETL processes, setting the timeout to 0 is useful when a second execution should be skipped rather than queued.
Unlike many SQL operations, sp_getapplock communicates its acquisition result through a return code.
|
Return code |
Description |
|---|---|
|
|
Lock granted immediately |
|
|
Lock granted after waiting |
|
|
Lock request timed out |
|
|
Lock request cancelled |
|
|
Selected as a deadlock victim |
|
|
Parameter validation or other call error |
The general validation principle is:
IF @ReturnCode >= 0
BEGIN
-- Lock successfully acquired
END
ELSE
BEGIN
-- Lock acquisition failed
END;
Important: Executing sp_getapplock does not guarantee that the lock has been acquired.
Developers must always check the return code before executing the protected operation.
Application locks can be explicitly released using sp_releaseapplock.
EXEC sp_releaseapplock
@Resource = 'DAILY_ETL_PROCESS',
@LockOwner = 'Session',
@DbPrincipal = 'public';
The resource name, ownership type and database principal must identify the corresponding acquired lock.
If the same owner acquires the same application lock multiple times, it must explicitly release it the same number of times to fully release it, unless the owning transaction or session terminates.
|
Operation |
Acquisition count |
Lock status |
|---|---|---|
|
Acquire lock |
1 |
Active |
|
Acquire lock again |
2 |
Active |
|
Release lock |
1 |
Active |
|
Release lock again |
0 |
Released |
When the same owner requests different lock modes on the same resource, SQL Server combines the requested modes.
The resulting stronger lock mode remains in effect until the lock is fully released.
For example, if a session acquires a Shared lock and subsequently acquires an Exclusive lock on the same resource, the exclusive mode remains active until the resource is fully released.
The APPLOCK_MODE() function returns the lock mode currently held by the specified owner.
SELECT APPLOCK_MODE(
'public',
'DAILY_ETL_PROCESS',
'Session'
) AS LockMode;
Possible results include:
NoLock
Shared
Update
Exclusive
IntentShared
IntentExclusive
SharedIntentExclusive
UpdateIntentExclusive
The APPLOCK_TEST() function determines whether a requested lock could currently be granted.
SELECT APPLOCK_TEST(
'public',
'DAILY_ETL_PROCESS',
'Exclusive',
'Session'
) AS CanAcquireLock;
|
Result |
Description |
|---|---|
|
|
Lock can be granted |
|
|
Lock cannot be granted |
However, APPLOCK_TEST() does not actually acquire the lock.
Another session may acquire the lock immediately after the test.
Therefore, it should not be used as a replacement for sp_getapplock when concurrency protection is required.
Application locks can be monitored using the SQL Server dynamic management view sys.dm_tran_locks.
SELECT request_session_id,
resource_type,
resource_database_id,
resource_description,
request_mode,
request_status,
request_owner_type
FROM sys.dm_tran_locks
WHERE resource_type = 'APPLICATION';
Important information includes:
|
Column |
Description |
|---|---|
|
|
Session requesting or holding the lock |
|
|
APPLICATION |
|
|
Database associated with the lock |
|
|
Application resource information |
|
|
Requested lock mode |
|
|
GRANT, WAIT or other lock status |
|
|
Lock ownership type |
SQL Server hashes application resource names internally.
Only the first 32 characters of the resource name are available in plain text after acquisition.
Monitoring other sessions requires appropriate server-level permissions.
Application locks participate in the standard SQL Server deadlock detection mechanism.
For example, Session 1 acquires resource A, while Session 2 acquires resource B. Session 1 then requests resource B, and Session 2 requests resource A.
SESSION 1 SESSION 2
| |
v v
Holds A Holds B
| |
v v
Requests B Requests A
| |
+----------+----------+
|
DEADLOCK
Both sessions are waiting for resources held by each other.
SQL Server can detect this situation and select one of the lock requests as the deadlock victim.
For an application lock request, sp_getapplock can return:
-3
An application lock deadlock return code does not automatically roll back the owning transaction.
The developer must implement the appropriate error handling and rollback logic.
A common prevention technique is to acquire multiple application locks in a consistent order across all processes.
Application locks are particularly useful for:
Preventing simultaneous execution of stored procedures.
Preventing overlapping scheduled jobs.
Synchronizing daily and monthly ETL processes.
Controlling data migration operations.
Coordinating data warehouse refreshes.
Protecting financial calculation processes.
Preventing concurrent invoice generation.
Coordinating operations across multiple tables and transactions.
For example, a daily data-loading process and a monthly data-reloading process can request the same exclusive application lock, ensuring that they cannot execute simultaneously.
DAILY_DATA_LOAD MONTHLY_DATA_RELOAD
| |
+------------+-----------+
|
v
DWH_MIGRATION_LOCK
(Exclusive)
|
v
Only one process executes
|
Advantages |
Disadvantages |
|---|---|
|
Native SQL Server functionality |
Requires explicit implementation |
|
No additional control table required |
All participating processes must follow the same locking convention |
|
Supports multiple lock modes |
Incorrect resource naming can cause conflicts |
|
Supports session and transaction ownership |
Deadlocks are possible |
|
Automatic release when ownership ends |
Session locks require careful lifecycle management |
|
Configurable waiting time |
Excessive locking can reduce concurrency |
|
Integrated monitoring |
Does not provide persistent execution history |
Important limitation: Application locks do not automatically prevent other sessions from modifying tables or executing procedures.
They only coordinate sessions that request locks on the same application resource.
All four major database management systems provide mechanisms for developer-controlled logical locking, although their ownership models, supported lock modes and release behavior differ.
|
Database |
Native functionality |
|---|---|
|
SQL Server |
|
|
Oracle |
|
|
PostgreSQL |
|
|
MySQL |
|
|
Capability |
SQL Server |
Oracle |
PostgreSQL |
MySQL |
|---|---|---|---|---|
|
User-defined locks |
Yes |
Yes |
Yes |
Yes |
|
Named resources |
Yes |
Yes |
Numeric keys |
Yes |
|
Session-level locks |
Yes |
Yes |
Yes |
Yes |
|
Transaction-level locks |
Yes |
Yes* |
Yes |
No |
|
Shared locks |
Yes |
Yes |
Yes |
No |
|
Exclusive locks |
Yes |
Yes |
Yes |
Yes |
|
Configurable timeout |
Yes |
Yes |
Via settings |
Yes |
|
Non-blocking acquisition |
Yes |
Yes |
Yes |
Yes |
|
Explicit release |
Yes |
Yes |
Session locks only |
Yes |
|
Deadlock detection |
Yes |
Yes |
Yes |
Yes |
* Oracle supports transaction-end release through the release_on_commit parameter of DBMS_LOCK.REQUEST.
SQL Server Application Locks provide a native mechanism for controlling concurrent execution at the business-process level.
Unlike traditional database locks, application locks allow developers to define what operation must be protected, rather than which database object must be locked.
They are:
✔ Explicitly requested by developers.
✔ Managed by the SQL Server Lock Manager.
✔ Independent of physical database objects.
✔ Configurable through lock modes and timeouts.
✔ Automatically released according to their ownership lifecycle.
This makes application locks particularly valuable for ETL, data warehouse management, scheduled processes and other operations where simultaneous execution must be controlled.