sql-server

13 Пост

oracle

17 Пост

postgresql

14 Пост

my-sql

2 Пост

common-sql

3 Пост

News

5 Новости

SQL Server Application Locks (sp_getapplock)

1. Overview

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.

 

2. What Problem Application Locks Solve

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.

Without application locks

     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.

With application locks

     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.

 

3. Application Locks vs Traditional Database Locks

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.

 

4. Application Lock Management Procedures

SQL Server provides two main system stored procedures for managing application locks.

Procedure

Description

sp_getapplock

Acquires an application lock

sp_releaseapplock

Releases an application lock

Additionally, SQL Server provides functions for checking application lock information.

Function

Description

APPLOCK_MODE()

Returns the current lock mode

APPLOCK_TEST()

Checks whether a requested lock can be granted

These functions allow developers to inspect application locks without acquiring a new lock.

 

5. General Syntax

Acquiring an application lock

DECLARE @ReturnCode INT;

EXEC @ReturnCode = sp_getapplock
    @Resource    = 'Resource_Name',
    @LockMode    = 'Exclusive',
    @LockOwner   = 'Transaction',
    @LockTimeout = 5000,
    @DbPrincipal = 'public';

Parameter description

Parameter

Description

@Resource

User-defined resource name

@LockMode

Requested lock mode

@LockOwner

Transaction or session ownership

@LockTimeout

Maximum waiting time in milliseconds

@DbPrincipal

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.

 

6. Application Lock Resource

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.

 

7. Application Lock Modes

SQL Server supports five application lock modes.

Lock mode

Description

Shared

Allows multiple compatible shared locks

Update

Allows shared access while preventing another update lock

Exclusive

Prevents other owners from acquiring conflicting locks

IntentShared

Represents shared-lock intent

IntentExclusive

Represents exclusive-lock intent

Lock compatibility matrix

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.

 

8. Application Lock Ownership

SQL Server supports two types of application lock ownership.

A. Transaction-level 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.

B. Session-level ownership

@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.

Ownership comparison

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

9. Lock Timeout

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

0

Return immediately if unavailable

1000

Wait up to 1 second

5000

Wait up to 5 seconds

60000

Wait up to 1 minute

-1

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.

 

10. Return Codes

Unlike many SQL operations, sp_getapplock communicates its acquisition result through a return code.

Return code

Description

0

Lock granted immediately

1

Lock granted after waiting

-1

Lock request timed out

-2

Lock request cancelled

-3

Selected as a deadlock victim

-999

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.

 

11. Releasing Application Locks

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.

Multiple lock acquisitions

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.

 

12. Checking Application Locks

APPLOCK_MODE

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

APPLOCK_TEST

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

1

Lock can be granted

0

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.

 

13. Monitoring Application Locks

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

request_session_id

Session requesting or holding the lock

resource_type

APPLICATION

resource_database_id

Database associated with the lock

resource_description

Application resource information

request_mode

Requested lock mode

request_status

GRANT, WAIT or other lock status

request_owner_type

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.

 

14. Deadlock Detection

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.

 

15. When Application Locks Are Useful

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
 

16. Advantages and Disadvantages

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.

 

17. Application Lock Equivalents in Other RDBMS

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

sp_getapplock, sp_releaseapplock

Oracle

DBMS_LOCK.REQUEST, DBMS_LOCK.RELEASE

PostgreSQL

pg_advisory_lock(), pg_advisory_xact_lock()

MySQL

GET_LOCK(), RELEASE_LOCK()

Feature comparison

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.

 

18. Summary

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.