SQL Server APP LOCK Mode: Syntax and Usage
In this article
You cannot call applock_mode as a standalone function in SQL Server. It is not a built-in system function. Instead, application locks are managed through the stored procedures sp_getapplock and sp_releaseapplock, and the lock mode is passed as a parameter to sp_getapplock. The mode values are Shared, Update, Exclusive, IntentShared, IntentExclusive, and Shared (with variations). This guide explains how to use these procedures correctly, what each lock mode means, and how to avoid common pitfalls.
What You'll Need
- SQL Server 2005 or later (application locks are available in all editions).
- Permission to execute
sp_getapplockandsp_releaseapplockin the database (members ofpubliccan execute by default, but the procedure checks permissions on the resource). - A database connection (the lock is scoped to the database and the principal).
- Basic familiarity with T-SQL and transactions.
Step-by-Step
- Understand the lock modes.
sp_getapplockaccepts a@LockModeparameter with these values:Shared– multiple sessions can hold the same shared lock simultaneously; blocks exclusive locks.Update– a middle ground that prevents deadlocks when multiple sessions intend to update; only one session can hold an update lock at a time, but shared locks can coexist.Exclusive– only one session can hold the lock; blocks all other lock modes.IntentShared– indicates intent to acquire a shared lock at a finer granularity; used internally, rarely needed directly.IntentExclusive– indicates intent to acquire an exclusive lock at a finer granularity.
Sharedif not specified. - Open a transaction. Application locks are held until the transaction commits or rolls back, or until explicitly released. Always wrap
sp_getapplockin a transaction to ensure proper release. For example:BEGIN TRANSACTION; DECLARE @result int; EXEC @result = sp_getapplock @Resource = 'MyAppLock', @LockMode = 'Exclusive', @LockOwner = 'Transaction', @LockTimeout = 5000; IF @result < 0 BEGIN ROLLBACK TRANSACTION; -- Handle lock acquisition failure END ELSE BEGIN -- Critical section COMMIT TRANSACTION; END - Choose the lock owner. The
@LockOwnerparameter can beTransaction(default) orSession. UseTransactionwhen you want the lock released automatically at the end of the transaction. UseSessionwhen you need the lock to persist beyond a transaction (e.g., across multiple batches); then you must explicitly release it withsp_releaseapplock. - Set a lock timeout. The
@LockTimeoutparameter (in milliseconds) controls how longsp_getapplockwaits for the lock. The default is the session'sLOCK_TIMEOUTsetting. A value of 0 means immediate failure if the lock is not available; -1 means wait indefinitely. Always handle the return code: 0 or positive indicates success, negative indicates failure (e.g., -1 timeout, -2 cancelled, -3 deadlock, -999 parameter error). - Release the lock. If you used
@LockOwner = 'Session', callsp_releaseapplockwith the same resource name and owner. For transaction-owned locks, the lock is released automatically on commit or rollback. Example:EXEC sp_releaseapplock @Resource = 'MyAppLock', @LockOwner = 'Session'; - Use a consistent resource name. The resource name is a string (up to 255 characters) that identifies the lock. Use a naming convention that includes the application name and purpose, e.g.,
'MyApp:OrderProcessing'. The lock is scoped to the current database and the principal (user) that owns it, so different users can acquire locks with the same name without conflict. - Test concurrency. Open two query windows. In the first, begin a transaction and acquire an exclusive lock. In the second, attempt to acquire the same lock with a short timeout; it should fail with a negative return code. This verifies the lock is working.
Common Mistakes
- Forgetting to handle the return code.
sp_getapplockreturns a status code, not an error. If you ignore it, your code may proceed without holding the lock, leading to race conditions. - Using
Sessionowner without releasing. Session-owned locks persist until the session ends or you explicitly release them. If you forget, other sessions may block indefinitely. - Assuming the lock is global. Application locks are scoped to the current database and the principal. Two different users can hold the same lock name simultaneously if they are different principals. To create a global lock, use a consistent principal (e.g., a dedicated user) or use a different mechanism.
- Mixing lock modes incorrectly. Using
Updatemode whereExclusiveis needed can allow concurrent access that violates your logic. Understand the compatibility matrix:Sharedis compatible withSharedandUpdate;Updateis compatible withSharedbut notUpdateorExclusive;Exclusiveis incompatible with all. - Not using transactions. If you use
@LockOwner = 'Transaction'but forget to begin a transaction, the lock is acquired and released immediately (auto-commit), providing no protection.
Tips
- Use
sp_getapplockto serialize access to external resources (e.g., a file, a web service) or to implement custom concurrency control beyond what row-level locking provides. - Keep the lock duration as short as possible to minimize blocking. Acquire the lock, perform the critical work, then commit or release.
- Choose
@LockTimeoutbased on your application's tolerance for waiting. A short timeout with retry logic is often better than a long block. - Monitor application locks using
sys.dm_tran_lockswhereresource_type = 'APPLICATION'. - Document your lock names and modes to avoid conflicts between different parts of the application.
Troubleshooting
- Lock not acquired (return code -1). The timeout expired. Check if another session holds a conflicting lock. Increase
@LockTimeoutor investigate the blocking session usingsp_who2orsys.dm_exec_requests. - Deadlock (return code -3). Two sessions are waiting for locks in a circular pattern. Use
SET DEADLOCK_PRIORITYor redesign to acquire locks in a consistent order. - Lock not released. If using
Sessionowner, ensuresp_releaseapplockis called. If usingTransactionowner, ensure the transaction is committed or rolled back. Check for open transactions in the session. - Permission denied. The procedure checks permissions on the resource. Ensure the user has the necessary rights; by default,
publiccan execute, but the resource name may be restricted. GrantEXECUTEonsp_getapplockif needed. - Unexpected blocking. Use
sys.dm_tran_locksto identify application locks and the sessions holding them. Queryresource_descriptionto see the lock name.
Frequently Asked Questions
Is applock_mode a real SQL Server function?
No. There is no built-in function named applock_mode. Application locks are managed via sp_getapplock and sp_releaseapplock, and the lock mode is specified as a parameter to sp_getapplock.
What is the difference between Shared and Update lock modes?
Shared allows multiple sessions to hold the lock concurrently, while Update allows only one session to hold it but is compatible with Shared. Update is useful to prevent deadlocks when multiple sessions intend to update a resource.
Can I use application locks across databases?
No. Application locks are scoped to the current database and the principal. To coordinate across databases, you would need to use a common database or a different mechanism.
How do I see which application locks are currently held?
Query sys.dm_tran_locks where resource_type = 'APPLICATION'. The resource_description column shows the lock name.
What happens if I don't release a session-owned lock?
The lock remains held until the session ends (connection closes) or you explicitly call sp_releaseapplock. Other sessions requesting a conflicting lock will block or time out.
Can I use application locks in a stored procedure?
Yes. You can call sp_getapplock inside a stored procedure, but ensure the transaction context is managed correctly. If the procedure is called within an existing transaction, the lock will be released when that transaction ends.