Handling Concurrent Session Access: Optimistic Locking and Race Prevention
ADK's DatabaseSessionService uses a real two-tiered locking design — in-process locks plus SELECT ... FOR UPDATE. Here is what that guarantees, and how to build optimistic-locking patterns on top of append_event semantics.
Published on • December 3, 2026
AI Assistant

Two requests hit the same session at the same moment — a user double-submits a form while a webhook fires, or two browser tabs resume the same conversation. Both handlers read login_count = 5, both compute 6, both append. The counter ends at 6 instead of 7: a classic lost update, and one of the hardest bug classes to reproduce because it only appears under load.
The reassuring part: ADK’s DatabaseSessionService documents a real, deliberate two-tiered locking architecture for exactly this problem. The less reassuring part: the locks protect event appends, not your read-modify-write logic. If you read state, compute a new value, and write it back across separate steps, no amount of SELECT ... FOR UPDATE inside append_event saves you from yourself. This article separates what the framework guarantees from what you must build — and shows the optimistic-locking patterns that live honestly on top of append_event semantics.
Prerequisites
- An ADK app with a persistent
SessionService(DatabaseSessionServicewithpip install google-adk[db], orInMemorySessionServicefor local reasoning). - Comfort with
EventActions.state_deltaandsession_service.append_event. - A scenario with genuinely concurrent access to one session: parallel tool calls, multiple invocations per session, or an app server with several workers.
1. Where the race actually lives
State is not a mutable map you edit — it is event-sourced. Every change travels as a state_delta on an event appended through session_service.append_event, and the service applies the delta when it persists the event. That design has a direct consequence for concurrency:
A delta is a full-value replacement per key, not an increment.
{"login_count": 6}does not mean “+1” — it means “setlogin_countto 6.”
So a lost update happens in your code’s gap:
# TWO concurrent handlers, both starting from the same read:
session = await session_service.get_session(app_name=..., user_id=..., session_id=...)
count = session.state.get("user:login_count", 0) # both read 5
# Handler A appends {"user:login_count": 6}
# Handler B appends {"user:login_count": 6} <-- A's increment is gone
Both appends succeed — nothing errored — but the second replacement silently overwrote the first. The race is in the read → compute → append window, not in the append itself.
2. What ADK guarantees: the two-tiered design
For DatabaseSessionService in Python, the docs describe two cooperating layers:
| Layer | Mechanism | Protects against |
|---|---|---|
| In-process locking | An internal, in-process lock serializes append_event calls for the same session | Multiple requests updating one session concurrently within the same process |
| Row-level locking | SELECT ... FOR UPDATE on PostgreSQL, MySQL, MariaDB | Multiple processes or replicas updating the same session concurrently |
InMemorySessionService follows the same principle at its own level: in-memory map mutations are guarded by service-internal locks. The common thread across all implementations is that append_event is thread-safe by design — concurrent appends to one session are serialized and applied one at a time.
What the locking does not do:
- It does not lock across your read of state and your subsequent append.
- It does not detect that your delta was computed from stale data.
- It does not provide a compare-and-swap (“append only if the value is still X”) primitive.
Those three gaps are where optimistic locking becomes an application-level concern.
3. The correct pattern: one event, one atomic delta
The first rule eliminates most races without any locking code of your own: put the entire read-modify-write inside a single event’s state_delta. Read the current value as late as possible, compute, and append both the new value and any derived keys in one append_event call:
from google.adk.events import Event, EventActions
async def bump_login_count(session_service, session, author="system"):
# Read as close to the append as possible.
current = session.state.get("user:login_count", 0)
changes = {
"user:login_count": current + 1, # recomputed value, full replacement
"user:last_login_ts": time.time(),
"task_status": "active",
}
event = Event(invocation_id=..., author=author,
actions=EventActions(state_delta=changes))
await session_service.append_event(session, event) # serialized by the service
Because append_event is serialized per session, two such calls cannot interleave their writes — but they can still both have read 5. The window is now one small critical section instead of an entire handler, which is the practical win. For values that must be exactly right under contention, add the second pattern.
4. Optimistic locking: version, compare, retry
Optimistic locking is the classic read version → compute → write with version check → retry on conflict loop. Honest caveat: ADK does not expose a compare-and-swap on append_event — the delta is applied unconditionally. So the version check lives in your application code, executed on the next read:
async def safe_increment(session_service, app_name, user_id, session_id):
for attempt in range(5):
session = await session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session_id
)
version = session.state.get("state_version", 0)
count = session.state.get("user:login_count", 0)
changes = {
"user:login_count": count + 1,
"state_version": version + 1, # bump the version in the SAME delta
}
event = Event(invocation_id=..., author="system",
actions=EventActions(state_delta=changes))
await session_service.append_event(session, event)
# Re-read: if someone else bumped the version first, their write won.
check = await session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session_id
)
if check.state.get("state_version") == version + 1:
return check # our write landed
# else: conflict — loop and recompute from the new state
raise RuntimeError("session contention: max retries exceeded")
This works because the version travels inside the same delta as the value it protects — append_event’s serialization guarantees the pair lands together, and the post-write read tells you whether your pair was the one that stuck. It is genuinely “optimistic”: you never block a writer, you detect conflicts after the fact and recompute.
5. Choosing a strategy
| Strategy | Where it lives | Best for | Cost |
|---|---|---|---|
| Single-event delta (§3) | Application | Low-contention, per-invocation updates | Near zero — just write discipline |
| Version + retry (§4) | Application | Counters, balances, any exact read-modify-write | Extra read per write; retry under contention |
| In-process serialization | DatabaseSessionService | Same-process concurrent requests | Free — already built in |
Row-level FOR UPDATE | DatabaseSessionService | Cross-process / multi-replica writes | Free — already built in |
| Single-writer queue | Application architecture | Very hot sessions (one logical writer) | Throughput ceiling per session |
Two practical notes:
- Never mutate a fetched
Sessiondirectly (my_session.state[...] = ...). That bypassesappend_event, bypasses every lock in the table above, and can lose data outright. All mutations go throughoutput_keyorEventActions(state_delta)appended viasession_service.append_event— thread-safe by design. - Guard read-modify-write inside one event’s delta. If two values must stay consistent (
balanceandbalance_version), write them in the samestate_delta; the serialized append applies them as one unit.
Checklist
- All state mutations go through
append_event(viaoutput_keyorEventActions.state_delta) — never a directly mutatedSession. - Read-modify-write computations happen as late as possible, in one event’s
state_delta. - Related values that must stay consistent are written in the same delta.
- Exact counters/balances use a version key bumped alongside the value, with a post-write verify + retry loop.
- The chosen
SessionServicematches the deployment:DatabaseSessionServicefor multi-process (its two-tiered locking is why). - Async drivers are configured for the database (
asyncpg,aiomysql,sqlite+aiosqlite). - Retry loops have a bounded attempt count and a failure path.
- The team knows
append_eventis serialized but stale reads are not — the race lives in the read-compute gap.
Conclusion
ADK gives you a solid floor: append_event is thread-safe by design, DatabaseSessionService serializes same-session appends in-process and guards cross-process writes with SELECT ... FOR UPDATE row locks. What it deliberately does not do is reach into your handler and fix a read-modify-write that spans several steps. Keep each mutation in a single event’s state_delta, and layer optimistic version-check-retry on the writes that must be exact. Do both, and the double-submit that used to silently drop an increment becomes a retry you will never notice.