This document describes the design philosophy behind the CockroachDB Spring Boot Starter, how the repository is organized, and the internals of the starter itself (packages, auto-configuration, advisor ordering). The rules for the getting-started guides live in guides.md, and the rules for how changes are scoped and tracked in rules.md.
The starter exists to make Spring applications work well on CockroachDB. Every design decision follows from that, and from the principles below. When a change seems to need an exception to one of them, settle that first, in the issue or pull request.
The starter follows Spring Framework and Spring Boot conventions as closely as it can, so that nothing surprises a developer who already knows Spring. It doesn't invent parallel mechanisms; it enhances the Spring way just enough to support CockroachDB. When designing an API, start from the Spring counterpart and extend it:
| Need | Spring convention | What the starter does |
|---|---|---|
| Declarative transactions with retries | @Transactional |
@CockroachDBTransactional is a composed @Transactional (meta-annotation plus @AliasFor); plain @Transactional methods get retries too |
| Programmatic transactions | TransactionTemplate / TransactionOperations |
CockroachDBTransactionTemplate extends TransactionTemplate, CockroachDBTransactionOperations extends TransactionOperations |
| Turning a feature on | @EnableTransactionManagement, applied by Boot's auto-configuration |
@EnableCockroachDBTransactionManagement, applied by the starter's auto-configuration, which backs off when the application declares it |
| Configuration | Boot @ConfigurationProperties |
cockroachdb.* properties with defaults, overridable per method or per template |
| Hooking into behavior | AOP advisors, TransactionExecutionListener, BeanPostProcessor |
The retry advisor wraps Spring's transaction advisor; the per-transaction region is bound by a transaction listener |
Consequences:
- Spring keeps doing Spring's job. Transactions are started, committed and rolled back by Spring's transaction infrastructure, with every
@Transactionalattribute meaning what it always has. The starter adds what CockroachDB needs (40001 retries, per-transaction regions) around it, rather than reimplementing it. - Names say what the Spring counterpart is.
CockroachDBTransactionTemplate, notCockroachDBTemplate, which reads like aJdbcTemplatesibling. - Differences from Spring are deliberate and documented. For example,
@CockroachDBTransactionaldefaults to SERIALIZABLE isolation where@Transactionaldefaults to the database default. Each one is called out where the user meets it.
Default to package-private, not public. A class, constructor, method or field is public only when users need it (it's part of the starter's API) or when another package in the starter needs it, and then only that member. IDEs and code generators tend to make everything public; don't accept that default. Every public type and member is something users can come to depend on, which makes it hard to change before 1.0 and harder after.
- Prefer a package-private class, with package-private constructors, for implementation pieces such as interceptors and helpers.
- When a type must be
publicbecause another package uses it, keep its other members package-private orprivate. - Spring doesn't need
publiceither: it can create beans from package-private classes. - Where this principle and Spring conventions conflict, the Spring convention wins.
@Beanmethods in auto-configurations staypublic, as they are in Spring Boot itself, and so do@ConfigurationPropertiesaccessors. - Some members must be
publicfor Java or for reflection: interface method implementations, and methods discovered withgetMethods()(such as@AgentToolmethods). - Tests live in the same package as the code they test, so they don't need
publicaccess.
The starter follows Spring's null-safety approach, so its nullness reads the same as Spring Framework 7's to IDEs, Kotlin and NullAway. Every package under src/main/java has a package-info.java annotated with JSpecify's @NullMarked, which makes every type in it non-null unless it is annotated @Nullable. A new package gets that package-info.java too.
The rule: if a value can be null, its type says so. Annotate every parameter, return value, field, record component and type argument that can hold null with org.jspecify.annotations.Nullable, so code that reads it is forced to deal with null, and nowhere else. Places it is easy to miss:
- Overrides of Spring APIs keep Spring's nullness, return values included. NullAway rejects a non-null parameter where Spring's is
@Nullable, but it accepts a return narrowed from@Nullableto non-null (BeanPostProcessor.postProcessAfterInitialization,HealthIndicator.health, and so on);NullSafetyConventionsTestcatches those. For generic methods, keep Spring's bounds:<T extends @Nullable Object> T execute(TransactionCallback<T>). - Values from code that isn't null-annotated can be
nulleven when nothing says so: JDBC (ResultSet.getString), the servlet API, reflection (getAnnotation), Jackson-bound maps, and AspectJ. An@Aroundadvice returns whateverProceedingJoinPoint.proceed()returns, which isnullfor avoidmethod, so it is declared@Nullable Object. - Thread-locals.
ThreadLocal.get()returnsnulluntil a value is set, so declareThreadLocal<@Nullable T>, and make any field that stores aget()result@Nullable. NullAway doesn't check this (it ignores type-argument nullness on JDK classes); IntelliJ IDEA does. - DTOs bound by Jackson. Jackson leaves a reference field
nullwhen the JSON omits it or sendsnull, and@JsonIgnoreProperties(ignoreUnknown = true)doesn't change that. So every reference component of a record read from JSON is@Nullable(including map values and list elements, for exampleMap<String, @Nullable Object>), unless its compact constructor replacesnull(asCDCEnvelopeturns a missingpayloadinto an empty list). - Optional injection points. A
@RequestHeader(required = false)(and likewise for request parameters and other optional arguments) isnullwhen absent, so it is@Nullable. - Configuration properties. A property with a default (
private String authToken = "";) is non-null; one without a default is@Nullable.
The other side of the rule: don't null-check a value whose type is non-null. The type is the contract, so a check on it is dead code that suggests otherwise. When a method really accepts null (a test passes it, or the Javadoc promises it), make the parameter @Nullable and keep the check instead. A caller that passes null where it isn't allowed gets a NullPointerException. A builder whose build() needs a required field checks it in the constructor, which reads every field from the builder.
Mind where a type-use annotation goes: String @Nullable [] (a nullable array), float @Nullable [], String @Nullable ... columns, and Outer.@Nullable Inner for a nested type. @Nullable on a local variable is never needed: NullAway infers it.
Each feature area (transactions, metrics, CDC, AI, Continuum) has its own auto-configuration, gated by classpath conditions and cockroachdb.* properties. Transaction retries are on by default because every CockroachDB application needs them; heavier features such as CDC and AI are off until an application enables them.
The published jar targets Java 17 and is tested on every supported JDK (17, 21 and 25). Nothing in the starter requires GraalVM, a particular container runtime or a CockroachDB Cloud account; native-image support is provided through runtime hints, not required.
User-facing behavior is documented in the README and taught by executable getting-started guides that CI builds against every change (see guides.md). A change that alters what users see updates both in the same pull request.
The starter's users include the coding agents that write so much application code today, not only the people they work with. Both should find it as easy as possible to reach CockroachDB through the starter, and to use what it provides instead of rebuilding it. An agent that doesn't know the starter tends to hand-roll a 40001 retry loop, run SET crdb_region itself, or write its own changefeed plumbing.
- Conventional APIs are the first help. Because the starter extends Spring the Spring way, what a person or an agent already knows about Spring carries over, and the obvious code is usually the right code.
- Agents get a guide of their own. docs/agents/AGENTS.md tells the coding agents working in a user's application what the starter already does, which annotation or API fits each job, which configuration matters, and which patterns to avoid. It links to the README for details rather than repeating it. It ships inside the jar, at
META-INF/cockroachdb-spring-boot-starter/AGENTS.md, so every application has a copy that matches the version it uses, and it is published on GitHub Pages (with anllms.txtthat points to it), so users can reference the latest from their own agent instructions. - It stays accurate. Like the README, the agent guide changes in the same pull request as the API it describes. A guide that tells an agent to use something that no longer exists is worse than none.
cockroachdb-spring-boot-starter/
├── README.md User-facing reference for the starter
├── AGENTS.md Instructions for coding agents working in this repo
├── build.gradle The starter (the published library)
├── src/ Starter source and tests
├── docs/architecture.md This document
├── docs/guides.md Rules and structure for the getting-started guides
├── docs/rules.md Rules for how changes are scoped, tracked and reviewed
├── docs/agents/AGENTS.md Guide for coding agents in applications that use the starter
├── docker/ Local multi-node CockroachDB clusters for manual testing
├── examples/ Standalone example apps (one directory each, own Gradle build)
└── guides/ Executable getting-started guides
├── README.md Guide index and the end-to-end process for writing them
└── <slug>/ One directory per guide
The starter is the product. Everything in guides/ exists to teach someone how to use it; see guides.md for the rules every guide follows and guides/README.md for how to write one. examples/ holds fuller demo applications.
The root build includes every guide (guides/<slug>/initial and complete) and every example (examples/<name>, any directory with its own settings.gradle, included as example-<name>, which the example's own settings.gradle also sets as rootProject.name so IDEs such as IntelliJ IDEA show the same name) as a composite build, resolving the starter from this checkout instead of the published release. ./gradlew build builds and tests all of them, so a starter change that breaks a guide or an example fails before it ships; ./gradlew guides and ./gradlew examples build each set on its own.
cockroachdb-spring-boot-starter is a single Gradle module that uses Spring Boot auto-configuration to conditionally wire CockroachDB-specific beans. Each feature area has its own @AutoConfiguration class gated by properties, so applications only activate what they need.
src/main/java/com/cockroachlabs/data/
├── Core Layer
│ ├── annotation/ Declarative annotations (@CockroachDBTransactional, @FollowerRead, etc.)
│ ├── aop/ AOP aspects that intercept annotated methods (@FollowerRead)
│ ├── transaction/ 40001 retry advisor/interceptor, shared retry loop, per-transaction region listener
│ ├── autoconfigure/ Spring Boot auto-configuration and properties binding
│ ├── template/ CockroachDBTransactionTemplate / CockroachDBTransactionOperations — programmatic retry API
│ ├── region/ RegionContext (ThreadLocal), RegionResolver (strategy)
│ ├── jpa/ JPA entity listeners (RegionalByRowListener)
│ └── metrics/ Micrometer metric bindings for transactions
│
├── CDC Layer
│ ├── cdc/annotation/ @CockroachDBCDC annotation
│ ├── cdc/handler/ Webhook controller, handler registry, method invoker
│ ├── cdc/factory/ Programmatic changefeed management (requires spring-jdbc)
│ ├── cdc/metrics/ Per-endpoint CDC metrics
│ ├── cdc/test/ CDCTestHarness, CDCEventBuilder
│ └── cdc/autoconfigure/ CDC auto-configuration classes
│
└── AI Layer
├── ai/annotation/ @VectorSearch, @SemanticSearch, @VectorColumn
├── ai/aop/ Vector/Semantic search aspects
├── ai/metrics/ AI metrics (search count, latency, results)
└── ai/autoconfigure/ AI auto-configuration and properties
Each feature area registers its own auto-configuration class:
| Class | Gate | Purpose |
|---|---|---|
CockroachDBAutoConfiguration |
Always active | Transaction retry advisor, template, region listener and beans |
CockroachDBMetricsAutoConfiguration |
Micrometer on classpath | Transaction metrics |
CockroachDBMultiregionAutoConfiguration |
Hibernate on classpath (on by default, cockroachdb.multiregion.mode=warn) |
Startup check that @GlobalTable/@RegionalByRow annotations and the live schema agree, in both directions |
CockroachDBCDCAutoConfiguration |
cockroachdb.cdc.enabled=true |
CDC webhook endpoint registration |
CockroachDBCDCMetricsAutoConfiguration |
CDC + Micrometer | CDC metrics |
CockroachDBAIAutoConfiguration |
cockroachdb.ai.enabled=true |
Vector search beans |
CockroachDBAIMetricsAutoConfiguration |
AI + Micrometer | AI metrics |
CockroachDB requires a new transaction after a serialization error (SQLSTATE 40001); retrying within the same transaction is not supported. CockroachDBTransactionAdvisor therefore runs at LOWEST_PRECEDENCE - 2, outside Spring's own transaction advisor (LOWEST_PRECEDENCE), and re-enters the rest of the interceptor chain once per attempt through ProxyMethodInvocation.invocableClone(), so every attempt gets a fresh transaction from Spring's TransactionInterceptor. It retries only at the outermost transactional call: when a transaction is already active, the method runs once and the 40001 propagates to the call that owns the transaction. Like Spring's own advisor, it is registered by an @Enable annotation, @EnableCockroachDBTransactionManagement (with an order attribute like @EnableTransactionManagement's), which the auto-configuration applies with its defaults when Spring's transaction advisor exists and the application hasn't declared it; the auto-configuration runs after Boot's TransactionAutoConfiguration. At startup the advisor fails fast if Spring's transaction advisor is missing or ordered at or before it.
@CockroachDBTransactional is a composed annotation, meta-annotated with @Transactional and redeclaring its attributes with @AliasFor, so Spring's transaction support handles propagation, isolation, timeouts, rollback rules, qualifiers and labels; the starter adds only retry settings and a region. The retry advisor matches through the same TransactionAttributeSource as Spring's transaction advisor, so plain @Transactional (on methods, classes or interfaces), composed annotations and jakarta.transaction.Transactional all get retries, unless cockroachdb.retry.apply-to-transactional-methods=false. CockroachDBTransactionTemplate extends TransactionTemplate and implements CockroachDBTransactionOperations (which extends TransactionOperations), mirroring Spring's template/operations split. The annotations and the template share one retry loop (SerializationRetry), so a fix to retry behavior lands in one place.
CockroachDB has no session variable for a region: in a REGIONAL BY ROW table, crdb_region is a column. So the starter runs no SQL for the region. It binds the region to RegionContext for one transaction, and RegionalByRowListener copies it into the @CrdbRegion field of each @RegionalByRow entity on @PrePersist. The region therefore homes new JPA rows only; it doesn't route queries, pick a gateway node, or affect rows written with raw SQL.
The region belongs to a transaction, and each retry is a new one, which no advisor ordered around Spring's transaction advisor can track. CockroachDBRegions is a TransactionExecutionListener that the starter registers with every ConfigurableTransactionManager bean. Retried methods and the template bind a scope on the current thread. When a transaction begins inside that scope, the listener resolves and validates the region in beforeBegin, before the transaction manager acquires a connection, so an invalid region fails cleanly; in afterBegin it binds the region to RegionContext and registers a synchronization that restores the previous value on completion. @FollowerRead suppresses it, since a follower-read transaction is read-only and has no rows to home.
Multi-region support uses a priority chain: annotation or template setting > ThreadLocal (RegionContext) > RegionResolver bean > cockroachdb.region.default-region > @RegionalByRow(defaultRegion). With none of these the field stays null and the insert fails the column's NOT NULL constraint, unless the entity uses @DynamicInsert so the column default applies. This lets applications mix static routing (annotation), request-scoped routing (context/filter), and dynamic routing (GeoIP resolver).
cockroachdb.multiregion.mode (none, warn by default, validate) is named after spring.jpa.hibernate.ddl-auto but deliberately has no update: changing locality from the application at startup would let the schema drift from the migration history, would run on every replica that starts at once, and rewrites REGIONAL BY ROW tables. Instead the report carries the SQL that fixes each problem. The check is a SmartInitializingSingleton, so it runs after Flyway or Liquibase. It runs in both directions: annotated entities must match their tables, and every entity whose table is GLOBAL or REGIONAL BY ROW must carry the matching annotation, so the annotations stay a complete, trustworthy picture of the schema. It takes table and column names from Hibernate's metamodel (so the application's naming strategy applies) and reads the database only through SHOW statements and information_schema, avoiding crdb_internal. Gaps (a locality not yet applied, a database not yet multi-region, a missing annotation) only warn by default, but a contradiction (@GlobalTable on a REGIONAL BY ROW table or the reverse, or annotations that disagree with each other) fails startup in warn mode too: the code and the schema disagree about where rows live, so one of them is wrong and running on is unsafe. Because it is on by default, it first confirms the database is CockroachDB (SELECT version()) and skips any other, so applications that test against another database see nothing. The token for this feature is multiregion; "locality" stays reserved for CockroachDB's own concept.
CDC handlers are discovered at startup via @CockroachDBCDC annotation scanning. The registry maps endpoint paths to handler methods. A single CDCWebhookController dispatches incoming webhook payloads to the correct handler, deserializing the JSON envelope into typed CDCEvent<T> objects using Jackson's TypeReference resolution.
@VectorSearch and @SemanticSearch are AOP-intercepted. The aspect builds the SQL query (including ORDER BY <vector_col> <=> $1 and optional filters), executes it via JdbcTemplate, and replaces the method's return value. This keeps the annotation declarative while the aspect handles SQL generation and parameter binding.
./gradlew build # Compile + test the starter, every guide and every example
./gradlew publishToMavenLocal # Install to ~/.m2- Required: Spring Boot Starter, Spring AOP, AspectJ, Spring TX, Spring JDBC
- Optional: Micrometer (metrics), Jackson (CDC JSON parsing), Spring Web (CDC webhook endpoint), JPA/Hibernate (entity annotations)
These apply to the starter itself and shape what guides can assume (guides.md):
- Built with GraalVM 25 and compiled with
--release 17, so the published jar runs on any Java 17+ JVM. - Main sources are checked by NullAway (through Error Prone, in JSpecify mode, for
com.cockroachlabs), and a violation fails the build. Tests are not checked.NullSafetyConventionsTestchecks by reflection what NullAway can't: that every package is@NullMarked, that overrides of Spring APIs keep Spring's nullness (return values included), and that@Aroundadvice returns@Nullable Object. See Null safety, the Spring way. ArchUnit can't take this over yet: it doesn't import type-use annotations such as@Nullable(TNG/ArchUnit#1382). - Tests run on JDK 17 by default; CI runs them on 17, 21 and 25.
- Integration tests use Testcontainers (
testcontainers-cockroachdb) and need only a container runtime.