Read-only transactions and gRPC in the Java backend

Yesterday I showed five Java backends on a $5 server. Small servers punish slow read paths first, because reads are most of what an app does. So the first thing we fixed was reads, and the second was making sure nobody can quietly break them again.

Every query was paying for writes

An ORM session collects your changes in memory and writes them out before each query, so the query sees them. That flush is right for code that writes. On a read path there’s nothing to save, so it’s work for nothing on every single query.

@Transactional(readOnly = true) now skips that flush. Commit still flushes, so nothing is ever lost.

@Transactional(readOnly = true)
public List<ProductView> browse(long storeId, String cursor) {
    return products.findPage(storeId, cursor, 48);
}

We also went through the read paths of our sample backends so each reads only what it shows. Bazaar, our storefront sample, now serves product pages in under 60 ms with 52 stores, 1,560 products and 120 shoppers, inside 1 GB of memory and one CPU. The flag is free, so it’s on every read path.

SQLite lies about read-only

Here’s the trap. PostgreSQL and MySQL refuse writes inside a read-only transaction. SQLite accepts the flag and enforces nothing. So you develop on SQLite, mark a method read-only, call something three levels down that saves an audit row, and every test passes. Then you deploy to PostgreSQL and the method fails in production.

We don’t think that bug should be possible. The build now follows every call a read-only method makes through your own classes and fails when it can reach a write operation: a repository save or delete, a @Modifying query, a Session update, or a read-write @Transactional method that joins the transaction.

flowchart LR V["CartService.view()
readOnly = true"] --> P[PricingService.quote] P --> A[AuditLog.record] A --> S["auditRepository.save()"] S -. build fails .-> X[[error: write reached]]

The error names the chain and tells you what to do:

@Transactional(readOnly = true) CartService.view reaches a write, which
PostgreSQL and MySQL reject in a read-only transaction: CartService.view ->
PricingService.quote -> AuditLog.record -> AuditRepository.save. Mark the
method read-write, or call the write through a REQUIRES_NEW method.

When that write path truly can’t run at run time, @SuppressWarnings("cn1:readonly-write") on the method says so. A chain that leaves your module becomes a warning, because the check can’t read a suppression in somebody else’s source.

Eight of our sample backends also carry a ScaleTest. Bazaar’s gives a store ten times the products and checks that a product page runs the same statements as before, and that the sitemap reads none of the products it doesn’t list. If you want your app to stay cheap to host, copy that test. It’s the cheapest performance insurance I know.

gRPC, both directions, all four shapes

The backend now serves and calls gRPC: unary, server streaming, client streaming and bidirectional. It runs on the HTTP/2 listener, so any stock gRPC client in any language can call it. The same services answer gRPC-Web over HTTP/1.1, which is what browsers and your Codename One app’s @GrpcClient use.

@GrpcService("demo.Greeter")
public class Greeter {
    @Rpc("SayHello")                       // unary
    public HelloReply sayHello(HelloRequest request) {
        return reply("Hello " + request.name);
    }

    @Rpc("Chat")                           // bidirectional streaming
    public void chat(Iterator<HelloRequest> in, StreamObserver<HelloReply> out) {
        while (in.hasNext()) {
            out.onNext(reply("Hi " + in.next().name));
        }
    }
}

Already have .proto files? mvn cn1:generate-grpc -Dcn1.grpc.target=backend writes the messages, a service interface to implement and a typed client. Messages are plain classes with @ProtoMessage and @ProtoField, and the build generates a codec for each one, so nothing is looked up by reflection at run time. Gzip, binary metadata, deadlines and a 4 MiB message cap are in, and the OpenTelemetry exporter can now ship over gRPC too.

flowchart LR G[grpcurl / Go / Kotlin service] -->|gRPC over HTTP/2| B[Codename One backend] W[Browser] -->|gRPC-Web over HTTP/1.1| B M[Your Codename One app
@GrpcClient] -->|gRPC-Web| B B -->|gRPC client| O[Other microservice]

One limit worth knowing: calls on a single HTTP/2 connection are served one at a time. Many clients open many connections, which is what clients do anyway.

GraphQL, schema first

GraphQL works the way Spring for GraphQL does. You write the schema in .graphqls files and @Controller methods resolve its fields. The build connects the two, so a resolver for a field the schema doesn’t have is a build error, not a log line you find a week later.

@Controller
public class BookController {
    @QueryMapping
    public Book book(@Argument("id") String id) {
        return library.find(id);
    }

    @MutationMapping
    public Book addBook(@Argument("input") BookInput input) {
        return library.add(input.title, input.authorId);
    }
}

@SchemaMapping, @BatchMapping for the N+1 problem, and subscriptions are there too.

Security expressions that cost an if

@PreAuthorize takes Spring Security’s expressions, and the build compiles each one into plain Java. There’s no expression language at run time, a typo is a build error, and checking a rule costs what an if costs.

@PreAuthorize("hasRole('ADMIN') or #owner == authentication.name")
public String activity(String owner) { ... }

@PreAuthorize("@documentPermissions.canEdit(authentication, #id)")
public void rename(@P("id") long documentId, String title) { ... }

Password storage gained {argon2} and {scrypt} hashes in the same format Spring Security writes, so users migrated from a Spring app sign in with their existing passwords. OAuth2 gained token introspection, private_key_jwt, pushed authorization requests, DPoP and OIDC logout.

And the rest of the list

  • Mail: IMAP and POP3 for reading, and DKIM signing so receiving servers can check that mail really came from your domain. Set three keys and every message is signed.
  • Migrations: Flyway style undo scripts (U3__add_created.sql takes back V3), callbacks and placeholders, with settings named like spring.flyway.
  • Tests: @Nested test classes.
  • Spring compatibility: server.servlet.session.* keys, a JSON 401 body, cn1.scheduler.enabled=false, and embedded static assets up to 32 MiB.

The pattern behind all of it is the same. If Spring Boot decides something at startup by scanning and reflecting, we decide it at build time. That’s how the server idles at 20 MB, and it’s why mistakes show up when you compile instead of when your users find them.

Try it

Generate a backend project from the Initializr, or read the backend data guide for the details. Tomorrow: a side scroller your server can verify.