100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Database Locking & Concurrency Cheat Sheet

Database Locking & Concurrency Cheat Sheet

Covers pessimistic and optimistic locking, isolation levels, deadlocks, and MVCC for handling concurrent reads and writes safely.

2 PagesAdvancedFeb 25, 2026

SQL Isolation Levels

The ANSI SQL transaction isolation levels.

  • READ UNCOMMITTED- Allows dirty reads (seeing uncommitted changes from other transactions); rarely used, not truly supported by Postgres
  • READ COMMITTED- Each statement sees only committed data as of when it started; the default in Postgres, Oracle, SQL Server
  • REPEATABLE READ- A transaction sees a consistent snapshot for its entire duration; prevents non-repeatable reads but allows phantom reads in some engines
  • SERIALIZABLE- Transactions behave as if executed one at a time; strongest guarantee, may abort transactions with serialization failures under contention
  • Dirty read / non-repeatable read / phantom read- Dirty: reading uncommitted data. Non-repeatable: same row changes between two reads in a transaction. Phantom: a repeated query returns new rows

Pessimistic Locking

Lock rows upfront to prevent concurrent modification.

sql
BEGIN;-- Lock the row so no other transaction can modify it until COMMITSELECT balance FROM accounts WHERE id = 1 FOR UPDATE;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;COMMIT;-- FOR UPDATE SKIP LOCKED: useful for job queues, skips already-locked rowsSELECT * FROM jobs WHERE status = 'pending'ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

Optimistic Locking

Detect conflicting writes with a version column.

sql
-- Add a version column to detect concurrent modificationALTER TABLE accounts ADD COLUMN version INT NOT NULL DEFAULT 0;-- Read the current version in the application-- SELECT balance, version FROM accounts WHERE id = 1;-- Update only succeeds if version hasn't changed since the readUPDATE accountsSET balance = balance - 100, version = version + 1WHERE id = 1 AND version = 5;-- If 0 rows affected, another transaction won the race; app retries or errors

Concurrency Concepts

Vocabulary for reasoning about concurrent access.

  • MVCC (Multi-Version Concurrency Control)- Postgres/MySQL InnoDB keep multiple row versions so readers never block writers and writers never block readers
  • Deadlock- Two transactions each hold a lock the other needs; the database detects the cycle and aborts one transaction automatically
  • Lock granularity- Row-level locks (most common) allow high concurrency; table-level locks are coarser and block more traffic
  • Advisory locks- Application-defined locks (e.g., Postgres pg_advisory_lock) not tied to a specific row, useful for coordinating app-level critical sections
  • Optimistic vs pessimistic- Pessimistic locks upfront assuming conflict is likely; optimistic checks for conflict only at write time, better for low-contention workloads

PostgreSQL Row & Table Lock Modes

The specific lock strengths Postgres exposes beyond a plain FOR UPDATE.

  • FOR UPDATE- Strongest row lock; blocks any other UPDATE, DELETE, or locking read on the same rows until commit
  • FOR NO KEY UPDATE- Like FOR UPDATE but doesn't conflict with FOR KEY SHARE, letting foreign-key checks on other rows proceed concurrently
  • FOR SHARE- Read lock that blocks writers but allows other transactions to also take FOR SHARE on the same rows
  • FOR KEY SHARE- Weakest row lock, taken automatically by referencing foreign keys; blocks only key-modifying updates
  • ACCESS EXCLUSIVE- Table-level lock taken by DDL like ALTER TABLE or DROP TABLE; blocks all other access including plain SELECT
  • ROW EXCLUSIVE- Table-level lock automatically taken by UPDATE/DELETE/INSERT; conflicts with ACCESS EXCLUSIVE but not with itself

Diagnosing and Retrying Deadlocks

Inspect blocking chains live and handle serialization failures in application code.

sql
-- Find who is blocking whom right nowSELECT blocked.pid AS blocked_pid,       blocked_stmt.query AS blocked_query,       blocking.pid AS blocking_pid,       blocking_stmt.query AS blocking_queryFROM pg_locks blockedJOIN pg_locks blocking  ON blocked.locktype = blocking.locktype AND blocked.database IS NOT DISTINCT FROM blocking.database AND blocked.relation IS NOT DISTINCT FROM blocking.relation AND blocked.pid != blocking.pidJOIN pg_stat_activity blocked_stmt ON blocked_stmt.pid = blocked.pidJOIN pg_stat_activity blocking_stmt ON blocking_stmt.pid = blocking.pidWHERE NOT blocked.granted AND blocking.granted;-- Force a lock wait timeout so a stuck transaction fails fast instead of hangingSET lock_timeout = '5s';-- Application retry loop pseudocode:-- Postgres error code 40P01 = deadlock_detected, 40001 = serialization_failure-- for attempt in range(3):--     try: run_transaction(); break--     except (DeadlockDetected, SerializationFailure): backoff_and_retry()

SSI Write Skew Under SERIALIZABLE

Postgres's Serializable Snapshot Isolation catches anomalies REPEATABLE READ misses.

sql
-- Classic write-skew: two on-call doctors both check "is someone else on call?"-- and both go off duty, violating the invariant "at least one doctor on call"BEGIN ISOLATION LEVEL SERIALIZABLE;SELECT count(*) FROM doctors WHERE on_call = true;  -- sees 2-- ... app decides it's safe to go off call ...UPDATE doctors SET on_call = false WHERE id = 1;COMMIT;-- Under REPEATABLE READ this commits fine on both sessions (no shared row is-- written by both), leaving zero doctors on call.-- Under SERIALIZABLE, Postgres detects the read/write dependency cycle and-- aborts one transaction with: ERROR: could not serialize access due to-- read/write dependencies among transactions -- the app must retry.

Distributed Locking Across Services

Coordinate mutual exclusion across processes when a single DB transaction isn't enough.

sql
-- Postgres advisory locks scoped to a session, released on disconnect/commitSELECT pg_advisory_xact_lock(hashtext('invoice-generation-job'));-- ... critical section runs inside this transaction ...-- lock auto-released at COMMIT/ROLLBACK, no risk of an orphaned lock-- Non-blocking variant for "only one worker should run this" patternsSELECT pg_try_advisory_lock(hashtext('nightly-report'));-- returns true/false immediately instead of waiting-- Redis-based lock (Redlock-style) for cross-database coordination, with a TTL-- so a crashed holder can't block forever:-- SET lock:invoice-job <uuid> NX PX 30000-- ... work ...-- DEL lock:invoice-job only if value still equals <uuid> (Lua script for atomicity)

Advanced Concurrency Failure Modes

Beyond the classic ANSI anomalies — patterns that bite in production.

  • Lost update- Two transactions read-modify-write the same row; the second commit silently overwrites the first's change unless a version check or FOR UPDATE prevents it
  • Write skew- Two transactions read overlapping data and write disjoint rows, each individually valid but jointly violating an invariant; only SERIALIZABLE catches it
  • Lock convoy- Many transactions queue behind one long-held lock, causing latency spikes that look like an outage even though no deadlock occurred
  • Starvation- A transaction repeatedly loses out to others under contention and never acquires the lock, distinct from deadlock (no cycle, just bad luck/priority)
  • Phantom via gap locks (InnoDB)- MySQL InnoDB uses next-key locks (row + gap) under REPEATABLE READ specifically to prevent phantom inserts that plain row locks would allow
  • Idempotency key pattern- Combine a unique constraint with ON CONFLICT DO NOTHING to make retried writes safe under at-least-once delivery, sidestepping lock contention entirely
Pro Tip

Always acquire locks (SELECT FOR UPDATE) in the same, consistent order across all code paths that touch multiple rows — inconsistent lock ordering is the number one cause of deadlocks under load, and the database can only abort one side, not prevent the collision.

Was this cheat sheet helpful?

Explore Topics

#DatabaseLockingConcurrency#DatabaseLockingConcurrencyCheatSheet#Database#Advanced#SQLIsolationLevels#PessimisticLocking#OptimisticLocking#ConcurrencyConcepts#Databases#Concurrency#CheatSheet#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse