Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Webhooks, Rank Races & Safe Payments with Postgres Locks

· 7 min read · Home Tech

In this article
  1. Why Webhooks Race and Why It Matters
  2. How Advisory Locks Work
  3. Choosing the Right Lock Scope
  4. Common Pitfalls and Misconceptions
  5. Advisory Locks vs. Alternatives
  6. Cost and Performance Considerations
  7. Safety and Reliability in Payment Processing
  8. Frequently Asked Questions

Yes, two webhooks racing to update the same rank or process the same payment can be made safe with PostgreSQL advisory locks, but only if you use them correctly. Advisory locks give you a lightweight, application-level mutex that works across multiple webhook invocations, preventing double-processing and race conditions without heavy table locks.

Why Webhooks Race and Why It Matters

Webhooks are HTTP callbacks that fire on events like a payment success or a score change. A common setup has two webhooks—say one from a payment provider and one from an internal service—both trying to update the same user's rank or payment status. If they run concurrently, you can get lost updates, double credits, or inconsistent rank calculations.

For example, consider a leaderboard where a user's rank is computed from their score. If two webhooks each add points and then recalculate the rank, they might both read the old score, add their points, and write back—one update gets lost. Similarly, a payment webhook that credits an account twice if retried after a network timeout is a classic problem.

PostgreSQL advisory locks are a built-in mechanism to serialize such operations. They are not row locks or table locks; they are application-defined locks stored in the database, visible across all connections. This makes them ideal for coordinating webhook handlers that may run on different servers.

How Advisory Locks Work

PostgreSQL provides two types of advisory locks: session-level and transaction-level. Session-level locks are held until explicitly released or the session ends. Transaction-level locks are automatically released at the end of the transaction. For webhook processing, transaction-level locks are usually safer because they tie the lock to the atomicity of your database changes.

You acquire a lock with pg_advisory_xact_lock(key) or pg_advisory_lock(key). The key is a bigint or two int4 values. You can use a hash of your business entity ID (like user ID or payment ID) as the key. For example:

SELECT pg_advisory_xact_lock(hashtext('user:' || user_id));

This ensures that only one transaction for that user runs at a time. The second webhook will block until the first completes, then proceed. If the first transaction rolls back, the lock is released, and the second can run.

For payment processing, you often want to check if a payment was already handled before applying changes. The lock ensures that check-and-insert is atomic. Without it, two webhooks for the same payment could both pass the check and both insert a credit.

Choosing the Right Lock Scope

You have to decide between session-level and transaction-level locks. Session-level locks are useful when you need to hold a lock across multiple transactions, but they require explicit release and are prone to leaks if your app crashes. Transaction-level locks are simpler and safer for most webhook scenarios because they auto-release.

Another decision is the lock key. Use a deterministic key derived from the entity you're protecting. For rank races, use the user ID or the leaderboard ID. For payments, use the payment ID or the subscription ID. Avoid using a single global lock for all operations—it would serialize everything and hurt performance.

Also consider using pg_try_advisory_xact_lock if you want to avoid blocking. It returns true if the lock was acquired, false otherwise. This is useful for idempotency checks where you want to skip processing if another webhook is already handling it. However, be careful: if you skip, you must ensure the other webhook will eventually complete successfully.

Common Pitfalls and Misconceptions

A frequent mistake is using a lock but not wrapping the entire critical section in a transaction. With pg_advisory_xact_lock, the lock is released when the transaction ends, so if you commit before finishing all updates, the lock is gone. Make sure all read-modify-write operations happen within the same transaction.

Another pitfall is using a lock key that is not unique enough, causing unnecessary contention. For example, using a constant key for all users would make all webhooks wait for each other. Hash the specific entity ID.

Some developers think advisory locks are persistent or replicated across databases. They are not. They exist only on the specific PostgreSQL instance. If you use multiple databases or a connection pooler that routes connections to different nodes, locks may not work as expected. In a single PostgreSQL cluster, they work across all connections.

Misconception: advisory locks are the same as row locks. Row locks protect a specific row from concurrent updates. Advisory locks are application-level and can protect any resource, even one not directly tied to a row. They are more flexible but require you to manage them correctly.

Advisory Locks vs. Alternatives

Other approaches to handle webhook races include:

  • Unique constraints with upsert: For payments, a unique index on the payment ID can prevent double-insert. But this only works if your operation is a single insert. For complex updates, it's not enough.
  • Optimistic locking: Use a version column and update with a WHERE clause checking the version. If the update affects zero rows, you know a concurrent change happened. This works but requires retry logic.
  • Distributed locks (Redis, ZooKeeper): These work across multiple database instances but add infrastructure complexity. Advisory locks are simpler if you're already using PostgreSQL.
  • Idempotency keys: Store a unique key in a table with a unique constraint. The first webhook inserts the key, subsequent ones fail. This is effective but requires a separate table and cleanup.

Advisory locks are often the best fit when you need to serialize a sequence of operations that involve multiple queries, and you want the lock to be automatically released on transaction end.

Cost and Performance Considerations

Advisory locks are lightweight. Acquiring a lock is a fast operation, comparable to a simple index lookup. They do not block other transactions unless they contend on the same key. The main cost is that a blocked webhook waits, which could increase response time under high contention.

However, you should avoid holding locks for long operations, like external API calls. Keep the critical section short—only the database operations. If you need to call an external service, do it before acquiring the lock or after committing, if possible.

For high-throughput systems, consider using pg_try_advisory_xact_lock and a fallback strategy. For example, if you can't get the lock, you could return a 409 Conflict and let the webhook retry. This avoids blocking and can improve throughput, but you need to handle retries properly.

Monitoring lock waits can help you tune your keys. PostgreSQL provides views like pg_locks to see active locks. You can detect if your lock keys are too coarse or if there are long waits.

Safety and Reliability in Payment Processing

For payments, safety is paramount. Advisory locks alone are not enough; you need a robust idempotency strategy. The lock ensures that only one webhook processes a given payment at a time, but you still need to handle retries after a crash.

A typical pattern is:

  1. Acquire a transaction-level advisory lock on the payment ID.
  2. Check if the payment has already been processed (e.g., look for a transaction record).
  3. If not, process the payment and insert the transaction record.
  4. Commit the transaction.

If the webhook crashes after acquiring the lock but before committing, the lock is released, and the retry will re-acquire it. The check ensures no double-processing.

You should also consider using a unique constraint on the payment ID in the transaction table as a backstop. Even if the lock fails somehow, the constraint will prevent duplicate inserts.

Another safety measure is to use two-phase commits if you're updating multiple databases, but that's overkill for most applications. For a single PostgreSQL database, advisory locks are sufficient.

Frequently Asked Questions

Can I use advisory locks for rank updates that involve a complex calculation? Yes. Acquire the lock on the user ID or the leaderboard ID, then do the calculation and update. This ensures no other webhook for the same user changes the score mid-calculation.

What happens if my webhook handler crashes after acquiring the lock? If you use transaction-level locks, the lock is released when the connection closes or the transaction rolls back. The next webhook will be able to acquire it. No permanent lock leak.

Do advisory locks work across multiple PostgreSQL instances? No. Advisory locks are local to a single database cluster. If you use read replicas or sharding, you need a distributed lock. For a single primary database, they work fine.

Is there a way to avoid blocking while still using advisory locks? Yes, use pg_try_advisory_xact_lock. It returns immediately, and you can decide to skip or retry. This is useful for idempotent operations where you can safely ignore a duplicate webhook.

Can I use advisory locks for non-webhook scenarios? Absolutely. They are general-purpose application locks. You can use them for any critical section that needs to be serialized across multiple app instances.

Are advisory locks safe for financial transactions? Yes, when combined with idempotency checks and unique constraints. They provide mutual exclusion, but you still need to ensure your business logic is correct and atomic.