Opik Backend opik-backend
Java backend patterns for Opik.
Use it when working in apps/opik-backend, designing APIs, database operations, or services.
- Our test
- —
- not tested yet
- GitHub stars
- 24k
- comet-ml/opik
- Added by
- 0
- members
- Updated
- Dec 6
- commit 316de6f
- Content
- 14 files
- no scripts · 111 KB
- License
- Apache 2.0
- free to use
What our test found
Not tested yet. Our model tries every skill on a realistic request and scores the result, the most popular skills first. Until then, the safety checks on the right still apply.
name: opik-backend description: Java backend patterns for Opik. Use when working in apps/opik-backend, designing APIs, database operations, or services.
Opik Backend
Architecture
- Layered: Resource → Service → DAO (never skip layers)
- DI: Guice modules, constructor injection with
@Inject - Databases: MySQL (metadata, transactional) + ClickHouse (analytics, append-only); pick per
- Services: stateless coordinators, no class cycles:
- Execution model: reactive end to end, entry points own schedulers:
Workspace Isolation
- Every query binds
workspace_id; workspace-scoped tables lead their key or index with it, so each query enforces isolation and workspace-wide scans stay on the key. - Every Redis key, lock name and cache key includes the workspace.
- Work on shared queues and streams can't trim, delete or starve another workspace's entries.
- Endpoints taking ids verify the ids belong to the caller's workspace before acting on them.
- Exception: cluster-wide jobs (planners, reconcilers, retention) read across workspaces by design. They take the workspace as an explicit parameter where they act on one, and the DAO method's Javadoc says why the query spans workspaces.
Naming Conventions
Plural Names (Resources, Tests, URLs, DB Tables)
- Resource classes:
TracesResource,SpansResource,DatasetsResource(notTraceResource) - Resource test classes:
TracesResourceTest,SpansResourceTest,DatasetsResourceTest(notTraceResourceTest) - URL paths:
/v1/private/traces,/v1/private/spans(not/v1/private/trace) - DB table names:
traces,spans,feedback_scores(nottrace,span,feedback_score)
Singular Names (DAO, Service)
- DAO classes:
TraceDAO,SpanDAO,DatasetDAO(notTracesDAO) - Service classes:
TraceService,SpanService,DatasetService(notTracesService)
// ✅ GOOD
@Path("/v1/private/traces")
public class TracesResource { }
// ✅ GOOD - DAO and Service use singular
public class TraceDAO { }
public class TraceService { }
// ✅ GOOD - test classes match plural resource name
public class TracesResourceTest { }
// ❌ BAD - singular test class
public class TraceResourceTest { }
// ❌ BAD - singular resource/URL
@Path("/v1/private/trace")
public class TraceResource { }
// ❌ BAD - plural DAO/Service
public class TracesDAO { }
public class TracesService { }Lombok Conventions
Records and DTOs
- Always annotate records/DTOs with
@Builder(toBuilder = true) - Use builders (not constructors) when instantiating records
- For internal records (built programmatically, never validated by Bean Validation), use Lombok
@NonNullon required fields — it generates a runtime null check at construction - For request-body DTOs validated via
@Validcascade (Jakarta validators like@NotNull/@NotBlank/@Size), use Jakarta annotations only — do not stack@NonNullon top. Bean Validation already enforces the contract at the API boundary; doubling up is redundant noise
// ✅ GOOD - internal record, Lombok @NonNull
@Builder(toBuilder = true)
record MyData(@NonNull UUID id, @NonNull String name, String description) {}
MyData data = MyData.builder()
.id(id)
.name(name)
.build();
// ✅ GOOD - request-body DTO, Jakarta validators only
@Builder(toBuilder = true)
public record MyRequest(
@NotNull UUID id,
@NotBlank String name,
@NotNull @Size(min = 1, max = 1000) @Valid List<MyItem> items) {}
// ❌ BAD - plain constructor (positional mistakes, less readable)
new MyData(id, name, null);
// ❌ BAD - @Builder without toBuilder
@Builder
record MyData(UUID id, String name) {}
// ❌ BAD - stacking @NonNull and @NotNull on the same field
public record MyRequest(@NonNull @NotNull UUID id) {}Primitives Over Boxed Types
Use a primitive (int, long, boolean) wherever the value is always present. Keep a boxed type only when null means something the primitive's default can't express. Use the same type for the same kind of value across a model: two counters of one kind shouldn't be Long and Integer, and one id shouldn't be UUID in one record and String in another.
// ✅ GOOD - always present; 0 already means "not retrying"
record Status(State state, int attempt, int maxAttempts) {}
// ❌ BAD - boxed for no reason, and mismatched types for the same kind of counter
record Status(State state, Long attempt, Integer maxAttempts) {}Dependency Injection
- Use
@RequiredArgsConstructor(onConstructor_ = @Inject)instead of manual constructors - Mark injected fields Lombok
@NonNull: Lombok generates the null check in the constructor. Jakarta@NotNullvalidates nothing there, so don't use it on constructor-injected fields or parameters
// ✅ GOOD
@RequiredArgsConstructor(onConstructor_ = @Inject)
public class MyService {
private final @NonNull DependencyA depA;
private final @NonNull DependencyB depB;
}
// ❌ BAD - boilerplate constructor
public class MyService {
private final DependencyA depA;
@Inject
public MyService(DependencyA depA) {
this.depA = depA;
}
}Interfaces
- Don't put validation annotations (
@NonNull) on interface method parameters - Keep interfaces free of implementation details
// ✅ GOOD
interface MyService {
void process(String workspaceId, UUID promptId);
}
// ❌ BAD - validation on interface
interface MyService {
void process(@NonNull String workspaceId, @NonNull UUID promptId);
}Java Style
- Import every type (static imports for AssertJ and WireMock); no fully qualified names inline, tests included.
- Switches over enums and sealed types list every case with no
default. For a non-sealed type, switch on its enum discriminator. - Comments: see .
- No
+to wrap any string, SQL or not: use a text block or.formatted(...). - A closed set of values is an enum implementing
HasValue, not a group ofStringconstants, which allow invalid values and drift from the code they mirror. - Avoid nested classes. Only
privatenested types are allowed; anything non-private (exceptions, records in a method signature, enums) is a top-level class in its own file, so callers don't depend onHost.Typeand it can be reused and tested alone. - A parameter every caller passes the same value to is a constant in its owner; the parameter only invites wrong values.
Critical Gotchas
Reactive Threading
After any async I/O call (ClickHouse, Redis, an async HTTP or AWS client), code runs on that client's thread. Blocking or I/O calls (MySQL, S3 and other AWS services, sync HTTP) and heavy CPU must move off it: follow the skill.
StringTemplate Memory Leak
// ✅ GOOD
var template = TemplateUtils.newST(QUERY);
// ❌ BAD - causes memory leak via STGroup singleton
var template = new ST(QUERY);List Access
// ✅ GOOD
users.getFirst()
users.getLast()
// ❌ BAD
users.get(0)
users.get(users.size() - 1)SQL Query Construction
Never build a query out of Java string operations. No +, no String.format / .formatted(...), no StringBuilder, no MessageFormat, no String.join over clauses. A query is declared once as a text block, and everything that varies goes through exactly one of two mechanisms:
| What varies | Mechanism | |-------------|-----------| | A value — id, name, timestamp, list of ids | :placeholder + .bind("placeholder", value) | | A fragment — predicate, sort clause, projected column, CTE | StringTemplate <if(x)>…<endif>, <else>, <x> + template.add("x", …) |
Why: interpolating values is the SQL-injection surface, and interpolating fragments hides which query a DAO actually runs — the declaration site stops being readable, and callers drift apart over time.
// ✅ GOOD - text block, values bound, structure via StringTemplate
@SqlQuery("""
SELECT * FROM datasets
WHERE workspace_id = :workspace_id
<if(name)> AND name like concat('%', :name, '%') <endif>
""")
// ❌ BAD - string concatenation
@SqlQuery("SELECT * FROM datasets " +
"WHERE workspace_id = :workspace_id " +
"<if(name)> AND name like concat('%', :name, '%') <endif> ")A predicate that differs between callers is a fragment, so it belongs in the template — not in a %s slot the caller fills in:
// ❌ BAD - caller splices the predicate in
private static final String TOKEN_USAGE_NAMES_TEMPLATE = """
SELECT DISTINCT name FROM (
SELECT usage FROM spans FINAL
WHERE workspace_id = :workspace_id
AND %s
) ...
""";
static String tokenUsageNames(String projectPredicate) {
return TOKEN_USAGE_NAMES_TEMPLATE.formatted(projectPredicate);
}
// caller: tokenUsageNames("project_id IN :project_ids")
// ✅ GOOD - both shapes live in the template, the caller picks one
private static final String TOKEN_USAGE_NAMES = """
SELECT DISTINCT name FROM (
SELECT usage FROM spans FINAL
WHERE workspace_id = :workspace_id
<if(project_ids)> AND project_id IN :project_ids <endif>
<if(project_id)> AND project_id = :project_id <endif>
) ...
""";
var template = TemplateUtils.newST(TOKEN_USAGE_NAMES);
template.add("project_ids", true);
...
statement.bind("project_ids", projectIds.toArray(new UUID[0]));A fragment that genuinely can't be enumerated in the template — a user-chosen sort field or filter clause — must be produced by the allow-listed builders (SortingQueryBuilder, FilterQueryBuilder), never assembled from raw request strings.
.formatted(...) stays correct for log and exception messages. The rule is about SQL text only.
Each query is written whole, so it can be read and pasted as it runs. Queries that differ only in a filter, a column set or an order are one StringTemplate query with <if(x)>…<endif> sections, exposed through DAO method overloads that delegate to it, not near-identical copies. Copy a block (column list, CTE) into a second query only when one template can't express both, and then guard the copies with a test that asserts they stay in sync. Never concatenate a block constant into a query.
No comments inside SQL text in Java sources (-- or /* */): put the rationale in the DAO method's Javadoc, where it is read with the method. Liquibase migrations are the exception: they use -- by design (see ).
Some %s query templates predate this rule. Don't copy them and don't add new ones.
Immutable Collections
// ✅ GOOD
Set.of("A", "B", "C")
List.of(1, 2, 3)
Map.of("key", "value")
// ❌ BAD
Arrays.asList("A", "B", "C")Generating UUIDs
Generate each id with the type its field expects, through IdGenerator, not a raw generator. Opik entity ids (traces, spans, experiments, datasets, ...) are time-ordered UUIDv7: ClickHouse sort keys and the UUIDv7 week bounds (see ) depend on ids rising with time.
Known v4 exceptions: workspace ids, which the auth service issues, and opaque random values that no table sorts on (OAuth tokens and client ids, correlation and query ids).
// ✅ GOOD - production code: the injected IdGenerator
UUID id = idGenerator.generateId();
// ✅ GOOD - tests: the same interface, from the test factory instead of injection
private static final IdGenerator ID_GENERATOR = TestIdGeneratorFactory.create();
UUID id = ID_GENERATOR.generateId();
// ❌ BAD - random v4 for an entity id
UUID id = UUID.randomUUID();
// ❌ BAD - raw generator instead of IdGenerator
UUID id = Generators.timeBasedEpochGenerator().generate();JSON Serialization
Use the JsonUtils helpers. They wrap Jackson's checked exceptions in UncheckedIOException, so no try/catch is needed. JsonUtils.getMapper() is legacy; don't add new callers.
// ✅ GOOD
String json = JsonUtils.writeValueAsString(status);
Status status = JsonUtils.readValue(json, Status.class);
// ❌ BAD - legacy mapper access plus hand-written checked-exception handling
try {
return JsonUtils.getMapper().writeValueAsString(status);
} catch (JsonProcessingException e) {
throw new UncheckedIOException(e);
}Comments
Write a method-level comment as Javadoc (/** ... */), not // above the signature, especially on protected extension points, where it documents the contract for overriders. Inline // comments stay for the why of a specific line. Comment only why, never what.
API Design
- Query parameters that accept lists: Use plural names from the start (e.g.,
exclude_category_namesnotexclude_category_name). Starting with a singular name and later adding a plural variant results in two redundant query params on the same endpoint. Plural names are backward-compatible since they work for both single and multiple values. - Optional query parameters: don't annotate
@QueryParamparameters with@Nullable; none of the backend's query params are. A@QueryParamwithout@NotNullor@DefaultValueis already optional and arrives asnullwhen omitted. Document what omitting it means in its@Schema(description = ...).@Nullablestays appropriate on API models and on internal methods, including private helpers inside resource classes.
User-Named Resources (name length)
A name longer than its column fails the INSERT with MysqlDataTruncation and surfaces as a 500. Every create and update/rename of a user-named resource must bound it:
- One constant per name, matching its column:
public static final int NAME_MAX_LENGTH = 150;on the resource model (e.g.Project.NAME_MAX_LENGTH), referenced everywhere the limit applies. Check the column width in the migration; not every name column is 150. - Validate declaratively on the create and the update/rename request models, and on every field that creates the resource implicitly (e.g.
project_nameon traces/spans/datasets):@Size(max = Project.NAME_MAX_LENGTH, message = "cannot exceed {max} characters").@Sizeis published asmaxLengthin the OpenAPI spec and reaches the generated SDKs. - Don't wrap it in a composed constraint annotation: swagger-core ignores constraints on the composing annotation, so the spec loses
maxLength(and anypatternit carried). Repeat@Sizewith the shared constant instead. - Normalize the same way on every path: if one path strips the name, all paths that store or look it up must strip it too, otherwise the same name maps to two resources.
- Service-level guard only for paths that bypass bean validation (OpenTelemetry, internal callers), counting the same way as those paths.
- Test create and rename with a
max + 1name (422) and with exactlymax(accepted).
Configuration
Settings, *Config classes and config-test.yml: .
Error Handling
Use Jakarta Exceptions
Throw a standard exception before creating a custom one. Add a subclass only when no standard type carries the meaning, and keep it a subclass of the standard exception so callers see the same status and body.
- A custom exception is a top-level class annotated with Lombok
@StandardException(seeRefusedHostException). - Always pass the cause when wrapping another exception.
throw new BadRequestException("Invalid input");
throw new NotFoundException("User not found: '%s'".formatted(id));
throw new ConflictException("Already exists");
throw new InternalServerErrorException("System error", cause);Retries
Retry with Reactor retryWhen and a spec from RetryUtils. Each spec retries only the errors that can pass on a second try, with backoff:
| Source | Spec | |--------|------| | ClickHouse | RetryUtils.handleClickHouseErrors(maxAttempts, minBackoff, maxBackoff) | | HTTP client | RetryUtils.handleHttpErrors(...): see | | A call with a deadline | RetryUtils.untilDeadline(...): see | | MySQL deadlock | RetryUtils.handleOnDeadLocks() around the whole inTransaction(...): MySQL rolls back all of it | | Dropped connection (SocketException, pool shut down) | RetryUtils.handleConnectionError() | | Any other source | No spec yet: add one to RetryUtils with an explicit filter, taking its policy as parameters |
Why: a bare Retry.backoff(...) has no filter, so it retries permanent errors (bad SQL, a memory limit, a 4xx) through every backoff before they surface. A hand-written loop has no jitter and no cap.
Retry only an idempotent operation: a read, or a write that lands the same way when repeated (an upsert on a stable key, a ReplacingMergeTree row with the same sorting and partition key, a request carrying an idempotency key). A timeout or a dropped connection can arrive after the server applied the call, so a non-idempotent one (a create without a stable id, an increment, a message the receiver doesn't deduplicate) can land twice: don't retry it, or make it idempotent first. See the Javadoc of handleClickHouseErrors.
// ✅ GOOD - retries only transient ClickHouse errors, with the policy from the feature's config block
return dao.findByIds(workspaceId, ids)
.retryWhen(RetryUtils.handleClickHouseErrors(config.getMaxRetries(),
config.getMinBackoff().toJavaDuration(), config.getMaxBackoff().toJavaDuration()));
// ❌ BAD - retries every error, permanent ones included
return dao.findByIds(workspaceId, ids).retryWhen(Retry.backoff(3, Duration.ofMillis(500)));Error Response Classes
- Simple:
io.dropwizard.jersey.errors.ErrorMessage - Complex:
com.comet.opik.api.error.ErrorMessage - Never create new error message classes
Logging
Format Convention
// ✅ GOOD - values in single quotes
log.info("Created user: '{}'", userId);
log.error("Failed for workspace: '{}'", workspaceId, exception);
// ❌ BAD - no quotes
log.info("Created user: {}", userId);Value Placement
Put the message first and the interpolated values at the end of the sentence, as a trailing name '{}' list. This keeps a stable literal prefix that stays greppable during a production debugging session — a message whose values are interleaved has no fixed substring to search for.
Applies to log.* format strings and to exception messages built with .formatted(...).
// ✅ GOOD - literal prefix first, values trailing
log.warn("Alert name is required, workspaceId '{}'", workspaceId);
log.debug("Webhook delivery failed, id '{}', status '{}'", eventId, status);
throw new DestinationGuardException("destination has no valid host, url '%s'".formatted(url));
// ❌ BAD - values interleaved, no greppable prefix
log.debug("Webhook '{}' failed with status '{}'", eventId, status);
throw new DestinationGuardException("destination '%s' has no valid host".formatted(url));Never Log
- Emails, passwords, tokens, API keys
- PII, personal identifiers
- Database credentials
- Throwable messages that can carry sensitive values: Redis and Redisson errors include the keys of the command. Log a sanitized class and message instead of the raw throwable.
Levels
info: a completed unit of work or a successful exit worth knowing about in production (job tick done, entity created, batch processed).warn: a handled failure or a degraded branch (a retry, a skip, a fallback, a rejected input that isn't the caller's routine error); pass the exception when there is one, sanitized per Never Log.error: an unexpected or unhandled failure, or anything an operator must act on; pass the exception, sanitized per Never Log when its message can carry keys or other sensitive values.debug: branch decisions and per-item detail needed only while investigating. Nothing per item atinfoon a hot path.- Log a caught exception once, where it's handled, not at every layer it passes through.
Reference Files
- - ClickHouse query patterns
- - TransactionTemplate patterns
- - PODAM, naming, assertion patterns
- - Liquibase format for MySQL/ClickHouse
- -
@RequiredPermissionsannotation guidance for endpoints - - Cursor-stream endpoints: request record, resource, DAO ordering and cursor, tests
- - Choosing the store; volume, retention and deletion of new data
- - Stateless services, cohesion, records and types, ownership
- - Execution model, schedulers and pools, Reactor context, cancellation, loop guards
- - Tunables in
config.yml,*Configclasses,config-test.yml - - Adding or changing a filter
FieldType: every file to update - - External services: client factory, user-supplied destinations, deadlines, retries, bodies, contracts, LLM prompts
- - Java-side memory, CPU and I/O of heavy methods; libraries; benchmarks
- skill - Which thread each step runs on;
Offload.blocking/cpu/blockingEachfor blocking calls, CPU steps and streams