Part 9: Application Development
Writing code that survives. Why you need retry logic for serializable transactions.
Developing for CockroachDB is 95% like developing for Postgres. The other 5% is handling transaction retries.
The 40001 Error
Because CockroachDB uses Optimistic Concurrency Control (OCC) for serializable isolation, transactions can conflict. When they do, one of them has to restart.
You will see this error: ERROR: restart transaction (SQLSTATE 40001).
Client-Side Retries
Your application code MUST handle this error and retry the transaction.
Most modern drivers have this built-in or have middleware for it.
# Pseudo-code for retry logic
while True:
try:
run_transaction()
break
except SerializationFailure:
continue
Idempotency
Because transactions can be retried, your operations should be idempotent. Don’t send an email inside a transaction unless you want the user to receive it 5 times!
Conclusion
Handling retries is a small price to pay for guaranteed consistency. In the final part, we’ll look at how to operate this beast in production.