Power of Eloquence

Mastering the Art of Technical Craftsmanship

Java Records Beyond DTOs: Production Patterns for Modern Backend Engineers

| Comments

TL;DR: Records are more than a way to cut getter boilerplate from DTOs. They are a modelling tool. Use them for value objects that check their own rules, closed sets of outcomes with sealed types, typed configuration, query projections and composite keys, and your production code gets smaller, safer and easier to read.

Generated AI image by Google Gemini Nano Banana

Introduction

Records have been final since Java 16, and in most codebases I’ve worked in they ended up in one place: the dto package. Request body in, response body out, job done. It’s a fair first use. It removes a lot of Lombok and hand-written equals().

But stopping there misses most of the point. Records were designed as transparent carriers for immutable data. Since Java 21 they also work with sealed interfaces and record patterns, and together these give you a lightweight way to do data-oriented programming in plain Java.

In this post, we’ll explore where records belong in production backend systems, and where they don’t. Whether you’re building a payments service on Spring Boot 3 or tidying up a legacy domain model, you’ll find patterns you can apply on Monday.

By the end of this post, you’ll understand:

  • How to use records as self-validating value objects (and why BigDecimal makes this matter)
  • How sealed interfaces + record patterns replace error-prone if/else chains
  • Where records fit with Spring configuration, JPA/Hibernate, caching and stream pipelines, plus the gotchas that bite in production

All plain-Java examples below were compiled and run on JDK 21. The Spring and Hibernate snippets assume Spring Boot 3.x and Hibernate 6.2+.

Section 1: Records as Value Objects

Compact constructors are your invariant guard

A record’s compact constructor runs before the fields are assigned. That makes it the natural place to validate and normalise input, so no invalid instance can ever exist.

Here’s a Money type, the classic value object in banking code:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Currency;
import java.util.Objects;

public record Money(BigDecimal amount, Currency currency) {

    // Compact constructor: no parameter list, no field assignments.
    // We can reassign the *parameters* before they're stored.
    public Money {
        Objects.requireNonNull(amount, "amount");
        Objects.requireNonNull(currency, "currency");
        // Normalise scale so 10.0 AUD and 10.00 AUD are equal (see below)
        amount = amount.setScale(currency.getDefaultFractionDigits(), RoundingMode.HALF_EVEN);
    }

    public static Money aud(String value) {
        return new Money(new BigDecimal(value), Currency.getInstance("AUD"));
    }

    public Money plus(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException(
                "Currency mismatch: " + currency + " vs " + other.currency);
        }
        return new Money(amount.add(other.amount), currency);
    }
}

// Money.aud("10.005").plus(Money.aud("0.1"))
// => Money[amount=10.10, currency=AUD]   (banker's rounding on 10.005 -> 10.00)

The same pattern works for typed identifiers. Passing three Strings around is how account numbers end up in customer-ID parameters:

public record AccountId(String value) {
    public AccountId {
        if (value == null || !value.matches("\\d{6}-\\d{8}")) {
            throw new IllegalArgumentException("Invalid BSB-account format: " + value);
        }
    }
}

Key points:

  • Validation lives with the data. You don’t need a separate validator class, and no caller can bypass it.
  • equals()/hashCode() are component-based. That’s why normalising the BigDecimal scale matters: new BigDecimal("1.0").equals(new BigDecimal("1.00")) is false.
  • Typed IDs make signatures self-documenting: transfer(AccountId from, AccountId to, Money amount).

Common Pitfalls to Avoid

  1. Shallow immutability

    • What happens: a record holding a List stores the caller’s list reference. The caller mutates it later, and your “immutable” record changes.
    • Why it’s problematic: you get subtle bugs in caches, events and concurrent code.
    • Better approach: make a defensive copy in the compact constructor.
    public record Statement(AccountId accountId, List<Money> lines) {
        public Statement {
            lines = List.copyOf(lines); // unmodifiable copy; also rejects null elements
        }
    }
  2. toString() leaking sensitive data

    • What happens: the generated toString() prints every component. Log a Customer record and the TFN or card number goes to Splunk.
    • Better approach: override toString() for any record that holds PII or secrets, and mask the field.
  3. Arrays as components

    • Records compare arrays by reference, not content. Prefer List.copyOf(...) or override equals/hashCode.

Section 2: Modelling Outcomes with Sealed Interfaces and Record Patterns

This is where records go well beyond DTOs. Java 21 finalised record patterns (JEP 440) and pattern matching for switch (JEP 441). Put them together with a sealed interface and you can model a closed set of outcomes that the compiler checks for you.

public sealed interface PaymentResult permits Approved, Declined, PendingReview {}

public record Approved(String txnId, Money amount)          implements PaymentResult {}
public record Declined(String reasonCode, String message)   implements PaymentResult {}
public record PendingReview(String caseId, Instant slaDeadline) implements PaymentResult {}

static String toCustomerMessage(PaymentResult result) {
    return switch (result) {
        // Deconstruct the record straight into variables
        case Approved(var txnId, var amount) ->
            "Paid " + amount.amount() + " " + amount.currency() + " (ref " + txnId + ")";
        // Guards with `when` handle special cases
        case Declined(var code, var msg) when code.equals("51") -> "Insufficient funds";
        case Declined(var code, var msg) -> "Payment declined: " + msg;
        case PendingReview(var caseId, var deadline) ->
            "Under review, we'll update you by " + deadline;
        // No default needed: the compiler knows the hierarchy is exhaustive
    };
}

Why this matters in production: if someone adds a Reversed outcome next quarter, every switch that doesn’t handle it fails to compile. With a default branch or an instanceof chain, the new case slips through to runtime instead. This works well for payment results, workflow states, validation errors and event types.

💡 On Java 22+, you can replace unused bindings like msg with _ (unnamed patterns, JEP 456).

Section 3: Records Across the Spring and Persistence Stack

Typed, immutable configuration

Spring Boot 3 binds through the constructor when a type has a single constructor, and a record always does. You don’t need setters, mutable state or @ConstructorBinding:

@Validated
@ConfigurationProperties(prefix = "payments.gateway")
public record GatewayProperties(
        @NotBlank String baseUrl,
        @DefaultValue("5s")  Duration connectTimeout,
        @DefaultValue("30s") Duration readTimeout,
        @DefaultValue("3")   int maxRetries
) {}

Enable it with @ConfigurationPropertiesScan or @EnableConfigurationProperties(GatewayProperties.class). Don’t annotate it with @Component, because Spring has to construct it through the binder.

Persistence: projections and embeddables, not entities

Be clear about the boundary here. Records can’t be JPA entities. Entities need a no-arg constructor, mutable state and (often) proxying, and records are final and immutable by design. Records still have two good uses here:

// 1. Read-model projections: fetch only what the screen needs
public record AccountSummary(String accountId, String nickname, BigDecimal balance) {}

public interface AccountRepository extends JpaRepository<AccountEntity, Long> {
    @Query("""
        select new com.example.AccountSummary(a.accountId, a.nickname, a.balance)
        from AccountEntity a where a.customerId = :customerId
        """)
    List<AccountSummary> findSummaries(Long customerId);
}

// 2. Embeddables (Hibernate 6.2+ supports records out of the box)
@Embeddable
public record Address(String line1, String suburb, String state, String postcode) {}

Projections are also a quiet performance win. You avoid loading full entity graphs, you skip dirty-checking, and there’s nothing for lazy loading to trigger.

Composite cache keys and stream intermediates

Because records get correct equals()/hashCode() for free, they make excellent map and cache keys. You no longer need string concatenation like from + "|" + to + "|" + date:

record FxRateKey(Currency from, Currency to, LocalDate asAt) {}

Map<FxRateKey, BigDecimal> rateCache = new ConcurrentHashMap<>();

Local records (declared inside a method) give you named tuples for stream pipelines, so you don’t need Map.Entry<String, BigDecimal> gymnastics:

record CategoryTotal(String category, BigDecimal total) {}

var topCategories = txns.stream()
    .collect(groupingBy(Txn::category,
             reducing(BigDecimal.ZERO, Txn::amount, BigDecimal::add)))
    .entrySet().stream()
    .map(e -> new CategoryTotal(e.getKey(), e.getValue()))
    .sorted(comparing(CategoryTotal::total).reversed())
    .toList();

Records also work well as event payloads for Kafka or SQS. They’re immutable, they’re safe to share across threads, and Jackson (2.12+) serialises them without extra annotations.

Section 4: “Withers”: Today vs Tomorrow

Immutable data means you create copies instead of mutating. For now, you write explicit “wither” methods:

public record RetryPolicy(int maxAttempts, Duration backoff, boolean jitter) {
    public RetryPolicy withMaxAttempts(int maxAttempts) {
        return new RetryPolicy(maxAttempts, backoff, jitter);
    }
}

JEP 468 (Derived Record Creation) proposes policy with { maxAttempts = 5; } syntax. At the time of writing it’s still a candidate JEP and isn’t in any released JDK, so don’t plan around it yet.

Best Practices and Recommendations

Do’s ✅

  • Validate and normalise in compact constructors, so invalid state can’t be represented
  • Defensively copy collections with List.copyOf / Map.copyOf
  • Pair records with sealed interfaces for closed outcome sets, and let the compiler check exhaustiveness
  • Use records for read models, projections, config, cache keys and events

Don’ts ❌

  • Don’t try to make records JPA entities. It fights the persistence model.
  • Don’t log records containing PII without overriding toString()
  • Don’t add default branches to sealed switches. That throws away exhaustiveness checking.
  • Don’t make records “god objects” with 15 components. Group related fields into nested records.

Performance Considerations

Records aren’t magic speed-ups, but they help in a few ways. They’re final and have no setters, so they’re safe to share across threads without locking. Projections cut ORM overhead. The JVM also treats record fields as trusted finals, which gives the JIT more room to optimise. The bigger win is usually the bugs you avoid, more than the CPU you save.

Troubleshooting Guide

Problem Cause Solution
Money values that look equal aren’t equals() BigDecimal scale differs (1.0 vs 1.00) Normalise scale in the compact constructor
Record “changes” after construction Mutable collection component List.copyOf(...) in the compact constructor
@ConfigurationProperties record not bound Annotated with @Component / not scanned Use @ConfigurationPropertiesScan or @EnableConfigurationProperties
Hibernate fails on @Embeddable record Hibernate < 6.2 Upgrade to 6.2+ (or write an EmbeddableInstantiator on 6.0/6.1)
Card numbers/TFNs in logs Auto-generated toString() Override toString() with masking

Further Reading

Conclusion

If records only live in your dto package, you’re using a fraction of what they offer. Treat them as a modelling tool. They give you value objects that enforce their own invariants, sealed outcome types the compiler checks for completeness, immutable configuration, lean read models and safe composite keys. Know where they stop, too: JPA entities and anything that genuinely needs mutable, identity-based state.

Your next steps:

  1. Find one primitive-obsessed signature in your codebase (String accountId, String customerId) and replace it with typed ID records.
  2. Pick one if/else instanceof chain or status-enum-plus-nullable-fields combo and refactor it into a sealed interface with records.
  3. Audit your existing records for mutable collection components and sensitive fields in toString().

Which of these patterns are you already using in production, and which ones have bitten you? Let me know in the comments.

Till next time, Happy Coding!

Comments