cockroachdb-developer-patterns

Coding rules for applications that use CockroachDB, a distributed SQL database, with Java frameworks such as JPA, Hibernate, Spring, or JavaEE. It also covers SQL queries that process sets of rows together.

In plain words
What is it for?
Use them when designing IDs, retries, entity mappings, batch writes, set-based SQL, or parallel queries in a CockroachDB application.
Why use it?
They help prevent slow inserts, transaction failures, inefficient database mappings, and query designs that do not suit a distributed database.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/cockroachdb/cursor-plugin/cockroachdb-developer-patterns
Clone the repo
git clone --depth 1 https://github.com/cockroachdb/cursor-plugin
Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 3,931 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.03931
Opus 5 $0.00000 $0.01965
Sonnet 5 $0.00000 $0.00786
Haiku 4.5 $0.00000 $0.00393

Measured yesterday against content hash 83342170fc74, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

cockroachdb-developer-patterns scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

rules/cockroachdb-developer-patterns.mdc · 474 lines

How it starts

The opening of the file, as written. The whole thing — 474 lines — stays where its author put it; the contents beside it link to each section on GitHub.

CockroachDB Developer Patterns — JPA, Spring, JavaEE & Set-Based SQL

Framework-specific patterns from JPA Best Practices for CockroachDB, Transaction Retries Series, Set-Based Operations, and cockroachdb-best-practices-demo.


1. JPA/Hibernate Identity Generators

❌ NEVER: Use GenerationType.IDENTITY with CockroachDB

// BAD: IDENTITY disables Hibernate JDBC batching entirely.
// Hibernate must execute each INSERT individually to retrieve the generated ID.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

✅ ALWAYS: Use UUID with GenerationType.AUTO

// GOOD: UUIDv4 generated in JVM — no DB round-trip, batching works, writes distributed
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(columnDefinition = "UUID")
private UUID id;

✅ Alternative: Explicit UUID generator for clarity

@Id
@GeneratedValue
@GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
@Column(columnDefinition = "UUID")
private UUID id;

If numeric PKs are unavoidable:

// Use unordered_unique_rowid() from CockroachDB — randomly distributed, not sequential
// Or use a custom generator that batches Hi-Lo allocation from a sequence in the JVM
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
@SequenceGenerator(name = "order_seq", allocationSize = 50)  // batch 50 IDs
private Long id;
// WARNING: Still creates some hot-spotting. UUID is strongly preferred.

2. Spring Boot Transaction Retry with AOP

The standard @Transactional annotation does NOT retry on 40001. Add an AOP aspect to intercept and retry.

✅ CORRECT: Spring AOP retry interceptor

@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE)  // Must run BEFORE @Transactional proxy
@Component
public class CockroachRetryAspect {
    private static final int MAX_RETRIES = 5;

    @Around("@annotation(transactional)")
    public Object retryOnSerializationFailure(
            ProceedingJoinPoint pjp, Transactional transactional) throws Throwable {
        for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
            try {
                return pjp.proceed();
            } catch (TransientDataAccessException ex) {
                Throwable root = ex.getMostSpecificCause();
                if (root instanceof SQLException sql
                        && "40001".equals(sql.getSQLState())
                        && attempt < MAX_RETRIES) {
                    long backoff = Math.min(
                        (long)(Math.pow(2, attempt) * 200 + Math.random() * 1000), 15000);
                    Thread.sleep(backoff);
                    continue;
                }
                throw ex;
            }
        }
        throw new ConcurrencyFailureException("Max retries exceeded for CockroachDB txn");
    }
}

Read the full file on GitHub · 474 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 474 lines · 0 tokens per session scan A 83342170fc74

Subscribe to this mod's changes

cockroachdb-developer-patterns is a cursor rule published in the GitHub repository cockroachdb/cursor-plugin (1 stars, last pushed 1mo ago), licensed Apache-2.0. It costs nothing until one of its globs matches a file; then it loads 3,931 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.