Java is an object-oriented programming language that allows engineers to produce software for multiple platforms. Our resources in this Zone are designed to help engineers with Java program development, Java SDKs, compilers, interpreters, documentation generators, and other tools used to produce a complete application.
Getting Started With Qdrant: Building Intelligent Search Applications With Java
Pitching Kotlin: An Engineering Leader's Guide to Legacy Modernization
Code review is the highest-leverage activity on most engineering teams, yet it is also the most expensive in terms of senior-developer time. What if you could offload a first pass to an LLM that understands Java idioms, common anti-patterns, SOLID principles, and security pitfalls — and get back structured, actionable feedback before a human even opens the PR? In this post, we will build exactly that: a self-contained Java application that accepts a Java source snippet, sends it to an LLM (OpenAI GPT-4o or a locally running Ollama model — your choice), and returns a structured list of code-quality findings with severity levels and suggested fixes. What you will build: A CodeReviewAssistant Java service backed by LangChain4j, which analyses Java code and returns structured improvement suggestions — runnable in under 10 minutes on your laptop. Prerequisites ToolVersionNotesJava JDK17+Records & sealed types usedMaven or GradleAny recentMaven snippets shown hereLangChain4j0.36.xLatest stable at time of writingOpenAI API key or Ollama—We show both No Spring, no frameworks — this is plain Java, so you can drop it into any stack. Step 1: Add LangChain4j to Your Project LangChain4j is the Java-native counterpart of the Python LangChain library. It gives you a clean, type-safe API over multiple LLM providers — OpenAI, Anthropic, Azure, Hugging Face, Ollama, and more — with zero vendor lock-in. Add the BOM and the provider module you want: XML <!-- pom.xml --> <dependencyManagement> <dependencies> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-bom</artifactId> <version>0.36.2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- Core --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j</artifactId> </dependency> <!-- Choose ONE provider below --> <!-- Option A: OpenAI (GPT-4o, GPT-3.5-turbo, …) --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-open-ai</artifactId> </dependency> <!-- Option B: Ollama (runs locally, no API key needed) --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-ollama</artifactId> </dependency> </dependencies> Tip — local-first development: Start with Ollama + codellama or mistral so you can iterate without burning API credits. Switch to OpenAI GPT-4o for production quality by changing one line. Step 2: Model the Review Output as a Java Record LangChain4j's Structured Output feature can instruct the LLM to respond with JSON that maps directly onto a Java type. We define our domain model first: Java // Finding.java public record Finding( String severity, // "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFO" String category, // e.g. "Null Safety", "Performance", "Security" String description, // human-readable explanation String suggestedFix // concrete code-level recommendation ) {} // CodeReviewResult.java import java.util.List; public record CodeReviewResult( String summary, List<Finding> findings ) {} Using Java Records keeps the model immutable and removes boilerplate. LangChain4j will automatically build the JSON schema from these types and include it in the system prompt. Step 3: Define the AI Service Interface LangChain4j's AI Services abstraction is the cleanest part of the library. You declare an interface, annotate it with prompts, and the library generates a proxy at runtime — no boilerplate, no manual HTTP calls. Java import dev.langchain4j.service.SystemMessage; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface CodeReviewService { @SystemMessage(""" You are a senior Java engineer performing a thorough code review. Analyse the provided Java code for: - Correctness and potential bugs - Null safety issues - Performance anti-patterns - Security vulnerabilities (injection, insecure randomness, etc.) - SOLID principle violations - Readability and naming conventions Return ONLY a JSON object matching the CodeReviewResult schema. Be concise but actionable. Severity: CRITICAL, HIGH, MEDIUM, LOW, INFO. """) @UserMessage("Review this Java code:\n\n```java\n{{code}\n```") CodeReviewResult review(@V("code") String javaCode); } How it works: The @SystemMessage sets the LLM's persona and instructions. The @UserMessage is the per-call prompt. @V("code") is a template variable — LangChain4j substitutes it at call time. Zero boilerplate. Step 4: Wire It All Together Now we create the LLM model, register our output type, and build the AI Service proxy. The entire wiring fits in one short class: Java import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.model.ollama.OllamaChatModel; import dev.langchain4j.service.AiServices; public class CodeReviewAssistant { public static void main(String[] args) { // ── Choose your provider ────────────────────────────────────────── // Option A: OpenAI (set env var OPENAI_API_KEY) var model = OpenAiChatModel.builder() .apiKey(System.getenv("OPENAI_API_KEY")) // never hardcode keys! .modelName("gpt-4o") .responseFormat("json_object") // enforce JSON mode .temperature(0.2) // low temp = consistent output .build(); // Option B: Ollama running locally on port 11434 // var model = OllamaChatModel.builder() // .baseUrl("http://127.0.0.1:11434") // .modelName("codellama") // .build(); // ───────────────────────────────────────────────────────────────── CodeReviewService reviewer = AiServices.builder(CodeReviewService.class) .chatLanguageModel(model) .build(); // ── Sample code to review ───────────────────────────────────────── String javaCode = """ public class UserService { private static Map<String, String> cache = new HashMap<>(); public String getUser(String id) { if (cache.containsKey(id)) return cache.get(id); String sql = "SELECT * FROM users WHERE id = " + id; // ... execute query return null; } } """; CodeReviewResult result = reviewer.review(javaCode); // ── Print results ───────────────────────────────────────────────── System.out.println("Summary: " + result.summary()); System.out.println(); for (Finding f : result.findings()) { System.out.printf("[%s] %s — %s%n", f.severity(), f.category(), f.description()); System.out.printf(" Fix: %s%n%n", f.suggestedFix()); } } } Step 5: Sample Output Running the above against that deliberately flawed snippet produces output like: Plain Text Summary: The code has a critical SQL injection vulnerability, a thread-safety issue with the shared HashMap cache, and returns null without documentation. [CRITICAL] Security — String concatenation builds a raw SQL query, making the method vulnerable to SQL injection attacks. Fix: Use PreparedStatement with parameterised queries: "SELECT * FROM users WHERE id = ?" with stmt.setString(1, id) [HIGH] Concurrency — HashMap is not thread-safe. Concurrent reads/writes will cause data corruption in multi-threaded environments. Fix: Replace with ConcurrentHashMap<>() or add explicit synchronisation. [MEDIUM] Null Safety — getUser() returns null without documentation. Callers have no contract to guard against NPEs. Fix: Return Optional<String> and document the empty-case semantics. [LOW] Performance — cache.containsKey() + cache.get() performs two lookups. Fix: Use cache.computeIfAbsent(id, k -> fetchFromDb(k)) instead. Going Further: Production Hardening 1. Streaming Responses for Large Files For large classes, swap the return type of your AI Service method to TokenStream and use onNext() / onComplete() to stream findings incrementally rather than waiting for the full response. 2. Memory and Conversation History LangChain4j's MessageWindowChatMemory lets you maintain multi-turn conversations — useful if you want the developer to ask follow-up questions about a specific finding. Java CodeReviewService reviewer = AiServices.builder(CodeReviewService.class) .chatLanguageModel(model) .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) .build(); 3. RAG: Ground Findings in Your Own Style Guide Use EmbeddingStore + ContentRetriever to inject excerpts from your team's coding standards into every review. The LLM will then apply your own rules rather than falling back on generic advice. 4. CI/CD Integration Wrap the service in a small CLI tool (using picocli), wire it into your GitHub Actions or Jenkins pipeline, and post findings as PR comments via the GitHub REST API. This enables a first-pass AI review before any human reviewer opens the PR. Key Takeaways LangChain4j AI Services let you express LLM interactions as plain Java interfaces — no HTTP plumbing, no JSON parsing.Structured Output (records + JSON schema) eliminates fragile string parsing; you get strongly typed results directly.Provider-agnostic design means you swap one builder line to move between OpenAI, Ollama, Anthropic, or Azure with zero business logic changes.Keep API keys in environment variables — never in source code.Start local (Ollama) to iterate fast, then promote to a hosted model for production quality. Further Reading LangChain4j official docsAI Services tutorialOllama — CodeLlama modelOpenAI Structured Outputs guide
OpenRewrite in a Real Enterprise Migration Recently, we modernized a 9-year-old enterprise application that involved two major changes happening together: Java 8 → Java 25Spring Boot 2.3.3 → Spring Boot 3.3.4 At the same time, we were also moving the application from a monolithic architecture toward microservices. One of the biggest challenges was the sheer volume of source-code changes. With Java 17 being the minimum required baseline for Spring Boot 3 and major namespace changes such as javax.* → jakarta.*, manually modifying a large codebase would have been time-consuming and risky. We decided to use OpenRewrite to automate the mechanical parts of the migration. The result was significant: 2,384 Java files were refactored in minutes. The manual effort that we estimated at roughly 5–7 days was reduced to automated transformation followed by code review and testing. But the most interesting part wasn't simply how much OpenRewrite changed. It was understanding what it could automate, what it couldn't, and where human judgment was still required. What Is OpenRewrite? OpenRewrite is an automated refactoring framework designed to transform source code using recipes. Instead of manually searching through thousands of files and applying the same transformation repeatedly, you define a recipe and let OpenRewrite perform the transformation consistently across the codebase. For large migrations, this is particularly useful for changes that are: RepetitiveSyntacticWell-understoodApplicable across many files The important distinction is that OpenRewrite automates code transformation. It does not understand every business rule or runtime behavior in an enterprise application. Our Migration The application was originally running on: Plain Text Java 8 Spring Boot 2.3.3 We moved toward: Plain Text Java 25 Spring Boot 3.3.4 One of the major changes introduced by Spring Boot 3 was the migration from the older Java EE namespace to Jakarta EE. For example: Java import javax.persistence.Entity; became: Java import jakarta.persistence.Entity; When you have thousands of source files, this is exactly the kind of transformation that should not be performed manually. Configuring OpenRewrite For our migration, we used the OpenRewrite Maven plugin: XML <plugin> <groupId>org.openrewrite.maven</groupId> <artifactId>rewrite-maven-plugin</artifactId> <version>5.41.0</version> <configuration> <exportDatatables>true</exportDatatables> <activeRecipes> <recipe>org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3</recipe> </activeRecipes> </configuration> <dependencies> <dependency> <groupId>org.openrewrite.recipe</groupId> <artifactId>rewrite-spring</artifactId> <version>5.20.0</version> </dependency> </dependencies> </plugin> We then executed: Shell mvn rewrite:run That's it. The tool analyzed the codebase and applied the configured recipe. What Happened? The results were better than we expected. 2,384 files changed. OpenRewrite modified approximately 2,384 Java files. The majority of the changes were mechanical framework migration changes. Some of the important changes included: 1. javax → jakarta A large number of imports were automatically migrated. For example: Java javax.persistence.* became: Java jakarta.persistence.* This is one of the areas where automated refactoring provides tremendous value. A developer doesn't need to manually locate every affected file. 2. Spring Batch API Changes Our application also contained Spring Batch code. Older APIs such as: Java JobBuilderFactory StepBuilderFactory needed to be migrated toward the newer builder APIs: Java JobBuilder StepBuilder OpenRewrite handled a significant portion of these changes automatically. This was particularly useful because Spring Batch code was spread across the application. 3. Other Spring Boot Migration Changes The Spring Boot migration recipes can also handle many other framework-level changes, including API and configuration changes. The exact transformations depend on the Spring Boot version and the recipe version being used. The OpenRewrite Spring Boot migration documentation provides the applicable transformation set and before/after examples. How Much Time Did It Save? This was probably the biggest practical benefit. Our initial estimate for manually performing the large-scale refactoring was approximately 5–7 days. OpenRewrite completed the core source transformation in minutes. We then spent approximately 4 hours reviewing the generated changes. This is an important distinction. We did not treat the generated code as automatically correct. The workflow was: Plain Text OpenRewrite ↓ Automated transformation ↓ Code review ↓ Compilation ↓ Unit/integration testing ↓ Manual fixes This turned the migration from a large manual refactoring exercise into a much more controlled process. But OpenRewrite Did Not Migrate Everything This was the most important lesson from our experience. OpenRewrite was extremely effective for structural and mechanical changes. However, there were areas where application-specific knowledge was required. The DAO layer was one example. Our application contained a significant amount of legacy SQL code. SQL Built Using String Concatenation Some queries were constructed using direct string concatenation. For example: Java String sql = "SELECT ... WHERE customer_id = " + customerId; These situations required manual intervention. The problem wasn't simply changing Java syntax. We needed to understand the SQL, parameter handling, and application behavior. OpenRewrite could transform Java source code, but it could not safely determine the business intent behind every SQL statement. Legacy Named Parameters We also discovered another interesting problem during testing. Some legacy DAO code used parameters such as: SQL :1 :2 The code compiled successfully after the migration. However, during runtime testing, some of these parameters failed to bind correctly. We had to manually replace them with explicit names such as: SQL :customerId :employeeId This was a good example of why successful compilation does not mean a migration is complete. The problem surfaced only when the application actually executed the affected code. What About Java 25? There is another important point when planning a Java 8 → Java 25 migration. Spring Boot migration and Java migration are related, but they are not the same transformation. OpenRewrite provides Java migration recipes as well. For example, there is a dedicated recipe for migrating to Java 25: Java org.openrewrite.java.migrate.UpgradeToJava25 The Java 25 migration guide currently describes this recipe as part of the rewrite-migrate-java recipe module. The important thing is to select the recipes appropriate for the actual migration path. For example: Plain Text Java 8 ↓ Java 17 ↓ Java 21 ↓ Java 25 or combine applicable migration recipes depending on the project's starting point and the changes required. A Java 25 recipe should not be treated as a replacement for the Spring Boot migration recipe. They address different parts of the modernization. Useful OpenRewrite Recipes for Java/Spring Modernization One of the things I like about OpenRewrite is that the migration doesn't have to stop with one recipe. Depending on the application, you can combine recipes for different modernization goals. Some useful categories include: Spring Boot For example: Java org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3 This was the recipe we used for our Spring Boot 3.3 migration. OpenRewrite also maintains Spring Boot migration recipes for newer Spring Boot versions. Java For Java modernization, OpenRewrite provides recipes such as: Java org.openrewrite.java.migrate.UpgradeToJava25 The Java migration recipes can target language/API modernization separately from Spring-specific changes. Other Framework/API Migrations The OpenRewrite recipe ecosystem also contains recipes for other common modernization scenarios. This is where OpenRewrite becomes more interesting than a simple search-and-replace tool. Recipes can encode relationships between APIs and perform structured transformations rather than blindly replacing text. What OpenRewrite Is Good At Based on our experience, I would categorize the work this way. Excellent Candidates for Automation Plain Text javax → jakarta Known API replacements Deprecated API migrations Repetitive source changes Large-scale mechanical refactoring Areas Requiring Engineering Judgment Plain Text Business logic SQL semantics Security behavior Application-specific configuration Runtime behavior This distinction is critical. You don't want to ask: "Can OpenRewrite migrate my application?" A better question is: "Which parts of my migration can be safely automated?" Automation Does Not Remove Testing One of the biggest mistakes would be to run: Shell mvn rewrite:run and assume the migration is finished. Our experience showed the opposite. The automated changes actually allowed us to spend more time on the areas that mattered. Instead of having developers spend days changing thousands of imports and APIs, we could focus our engineering effort on: Reviewing generated changesFixing application-specific issuesValidating SQL behaviorTesting Spring Batch behaviorValidating security configurationRunning integration testsInvestigating runtime failures The tool didn't remove engineering work. It moved engineering effort from repetitive refactoring to higher-value validation. Our Takeaway The most impressive part of OpenRewrite wasn't that it changed 2,384 files. It was that it allowed us to approach a large migration differently. Without automation: Plain Text Thousands of files ↓ Manual changes ↓ 5–7 days ↓ High risk of inconsistency With OpenRewrite: Plain Text Migration recipe ↓ 2,384 files transformed ↓ Minutes ↓ Code review ↓ Testing ↓ Manual fixes where required The lesson I took from the migration is simple: Automate the mechanical work. Keep human judgment for the work that requires application context. OpenRewrite doesn't eliminate the complexity of a Java/Spring modernization. But for a large legacy application, it can dramatically reduce the amount of repetitive work engineers need to perform — and make the overall migration much more controlled and repeatable.
DB changes can be streamed in real time via Oracle GoldenGate. Java applications can then consume them to validate/act on/route events without polling the DB. Goal Listen to real-time transactions in the DB, act on all operations within transactions, and maintain transaction boundaries with near real-time SLAs. Component Details 1. Source DB This is the source DB from which the Java service listens for transaction changes in real time. It can be any DB supported by the GoldenGate service (e.g., MySql/ Oracle). 2. OCI Source GoldenGate Service Deployment Input: DB Redo logsOutput: Trail file The GoldenGate service has two primary components: Extract and Replicat. Extract reads changes from the source DB in the form of redo and archive logs. It commits each transaction's DML operations until either COMMIT or ROLLBACK is identified. If it encounters a COMMIT, it stores the transaction in TRAIL files. If ROLLBACK is encountered, it discards those changes. The output of this deployment is a TRAIL file with an ordered list of all transactions that occurred in the source DB. 3. OCI Target GoldenGate Big Data Deployment Input: Trail files generated by traditional GG deploymentOutput: Ordered stream of operations within a transaction This is another deployment type that can be used for transaction management. We can use the DATA STREAMS feature instead, but this uses the AsyncAPI publish/subscribe interface, whereas big data deployment is a managed integration runtime for CDC delivery to Kafka. 4. Streaming Service Input: Trail files generated by traditional GG deploymentOutput: Ordered stream of operations within a transaction Ideally, Kafka keeps up with the scale of GoldenGate and downstream scalability. Kafka provides an option to add partitions while the partitions are receiving data. This feature is particularly useful for handling traffic bursts or batch SQL jobs on the source DB. 5. Java Service Kubernetes Deployment Input – Kafka messages, in this case individual operationsOutput – Application logic A Java application instance that can scale horizontally depending on the Kafka partition backlog. Use Case Java service is interested in listening to the entire transaction in the order that it is happening for a predefined set of tables.It does not want to listen to all the source table changesIt also does not want all columns of the changed row. It is interested in listening to only specific set of columns from given list of tables. Component Setup The detailed setup guide here can be used as general guidance, but I will focus on the specific changes needed to achieve the use case above. 1. Source DB Here we want to listen to redo logs from the source DB. To enable supplemental logging on the source DB, use the command below. SQL ALTER DATABASE ADD SUPPLEMENTAL LOG DATA In our use case, we also want to make sure we always get only the columns from the table that the Java service is interested in, and not all the columns. To enable table-specific supplemental logs, use the command below. SQL ALTER TABLE HR.EMPLOYEE ADD SUPPLEMENTAL LOG GROUP emp_group_loc (EMPLOYEE_ID, EMP_NAME, EMP_DEPARTMENT_ID); 2. OCI Source GG Deployment In this step, OCI source GG deployment is configured to listen to redo logs of the source DB. As per our use case the important step is to configure only required tables in Extract's parameter file. The list of tables basically makes sure transactions happening on only those tables will be identified by GG and will be collected in trail files. You can use this article to set up Extract. Example of parameter file for extract: SQL table HR.EMPLOYEE; Along with extract, a distribution path needs to be created within the same source deployment. This distribution path makes sure the target big data deployment can access the trail file records easily. The details to create the distribution path can be found in TASK 3 of the article. 3. OCI Target GoldenGate Big Data Deployment In this deployment, a process called 'replicat' is created; replicat reads transaction data from the distribution path created in step 2 above, then publishes those transactions. Replicat works using two configuration files. Parameter File Similar to Extract, Replicat also has a parameter file. This file contains mapping information on how operations from the source DB map to the target schema and table. Since we are not replicating transactions in the DB, a JSON with the target table mapped in the parameter file gets written to kafka topic instead. Example for a complete setup guide: use this guide. SQL MAP HR.EMPLOYEE, TARGET *.*; Properties File Three important parameters that decide how the source transactions get written to the target are 1. TopicMappingTemplate – Tells replicat about the target, where source transactions will be written, 2. opMode – How the source transaction will be written. Complete transaction or one operation at a time.3. keyMappingTemplate – This parameter is the hashing key used by the replicat Kafka producer. For all the parameters that are available in the properties file, please refer to section "11.2.10.1.3.2.2 Kafka Handler Configuration" in this guide. 4. Streaming Service and Java Consumer Service Since GG hashes based on transaction ID, it is guaranteed that all operations in a transaction will always be in the same partition. The Java service needs a consumer group used by all pods. At bootstrap, all pods register their client ID with the Kafka broker and reserve a partition. This mechanism makes sure a single pod always listens to one partition until a rebalance happens due to a pod going down or other reasons. This setup ensures the Kafka consumer in the Java service can poll and collect transactions while maintaining operation boundaries and sequence for downstream application logic within the same service. Separating polling logic from processing logic in the Java service helps avoid various timeout scenarios. We can dive deep into this mechanism in a follow-up article. Summary With this setup, we can guarantee that transactions at the source DB are accessed by a Java service in order and can run within a single transaction at a time. This workflow is useful for industries that need an eventing mechanism, such as fraud detection and financial applications, telecommunications and real-time billing, Retail and real-time inventory management, and AI and semantic search pipelines.
The Cookie That Never Came Back The first call authenticated the user. The second failed. I was integrating with a customer-provided SOAP service exposed through a single WSDL, with JAX-WS client classes generated by IBM Rational Application Developer from the WSDL and its XSDs. The first call authenticated the user and came back with a Set-Cookie header. Every call after it needed that cookie. The generated client sent none of it. Each invocation behaved as an independent conversation, and the workflow broke on its second step. No exception, no warning. Just a server that had forgotten who you are. The Built-in Answer, and Why It Failed The JAX-WS specification anticipated this: every proxy generated from a WSDL implements BindingProvider, and the spec defines a request-context property for exactly this purpose: Java CheckPort port = new Check().getCheckPort(); ((BindingProvider) port).getRequestContext() .put(BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); Set that flag, and the runtime is supposed to maintain session state. In most tutorials, this is where the article ends. Mine broke in deployment for three reasons: First is scope. The property is set on one proxy instance, and the runtime's cookie store lives with that proxy. RAD-generated code encourages pulling a fresh port per unit of work. Every fresh port gets a fresh store, so the authentication session is discarded when the method returns. Holding one proxy for the workflow fixes it, but pins the session lifetime to the object lifetime. Second is opacity. The spec does not say where the runtime keeps the cookie. The JDK's bundled implementation delegates to java.net.CookieHandler.getDefault(), null unless somebody installed one. IBM's runtime, which RAD-generated clients typically run on under WebSphere, does it its own way. Same client class, different behavior per container, and the failure is silent. Third is the obvious fix: install a default CookieManager inline. Java `CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));` A JVM-wide static. Fine in a standalone client, but inside an application server, it is shared by every deployed application and every outbound HTTP client in the JVM. It is also the wrong model for a server-side client: a CookieManager is built for a browser, where one cookie jar belongs to one user. A server handling concurrent requests would pool every user's session cookies into one store, and CookieManager applies RFC domain and path matching, so if the service sits behind a load balancer, the cookie is quietly dropped. The Options on the Table I wanted cookie handling scoped to the call, visible in the code, and independent of the container. The alternatives fell short. Holding one proxy for the whole workflow is the simplest change, but it marries the session to an object's lifetime, and the strain shows across components or threads. Installing a default CookieManager is one line and works in a standalone client. But inside an app server, it becomes shared mutable state across applications and users, which rules it out for anything concurrent. Hand-rolling the client on plain HTTP gives full header control with no container surprises, but you lose the WSDL tooling: generated types, binding, error handling. Too much machinery to rebuild for several operations. A custom SOAP handler was the fourth option: roughly sixty lines you own, sitting in the message path of the existing generated client. Nothing JVM-wide, nothing container-specific, nothing hand-edited in generated classes. The costs: you match the cookie by name instead of trusting RFC rules, and you own the stored value's lifecycle. Acceptable for this integration. How the Handler Works The contract is SOAPHandler<SOAPMessageContext>; the direction comes from a Boolean on the context. The listing below is illustrative, adapted from the class I used, and not presented as tested code. Java public boolean handleMessage(SOAPMessageContext ctx) { if (Boolean.TRUE.equals(ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY))) { attachCookie(ctx); } else { captureCookie(ctx); } return true; } @SuppressWarnings("unchecked") private void captureCookie(SOAPMessageContext ctx) { Map<String, List<String>> headers = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_RESPONSE_HEADERS); if (headers == null) { return; } for (Map.Entry<String, List<String>> entry : headers.entrySet()) { if (!"Set-Cookie".equalsIgnoreCase(entry.getKey())) { continue; } for (String raw : entry.getValue()) { String pair = raw.split(";", 2)[0].trim(); if (pair.startsWith("JSESSIONID=")) { SESSION_COOKIE.set(pair); } } } } @SuppressWarnings("unchecked") private void attachCookie(SOAPMessageContext ctx) { String cookie = SESSION_COOKIE.get(); if (cookie == null) { return; } Map<String, List<String>> existing = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_REQUEST_HEADERS); Map<String, List<String>> headers = (existing == null) ? new HashMap<>() : new HashMap<>(existing); headers.put("Cookie", Collections.singletonList(cookie)); ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } public boolean handleFault(SOAPMessageContext ctx) { return true; } public void close(MessageContext ctx) { } public Set<QName> getHeaders() { return Collections.emptySet(); } } Three details in that listing exist because earlier versions broke. Copying the existing request headers before adding Cookie keeps the handler additive: putting a fresh map into HTTP_REQUEST_HEADERS replaces whatever was already there, and my first version did exactly that, until another handler down the chain set a custom authorization header that then vanished. Matching the header name case-insensitively is for portability, since a case-insensitive map is an implementation choice, not a spec guarantee. Splitting on the first semicolon keeps response attributes such as Path, Expires, and HttpOnly out of the request; echoing them produces a Cookie value the server will not parse. Iterating over every value rather than taking index zero covers responses that set more than one cookie, where the session cookie is not guaranteed to be first. Why ThreadLocal, and Where It Bites The integration ran several workflows concurrently, so a static field would leak one user's session into another's request. A ThreadLocal gives each thread its own value, which fits a workflow that runs start to finish on one thread. The cost is that thread pools reuse threads. If a workflow ends without clearing the value, the next request on that thread inherits a stale session cookie. In the worst case, it sends one user's session identifier on another user's behalf. Clearing it when the workflow ends closes that hole: SESSION_COOKIE.remove(); Note that close() is intentionally empty: the container calls it at the end of each message exchange, not the workflow, so clearing there would discard the cookie from the authentication call. Cleanup belongs at the logout step or in a finally block around the workflow. And if the workflow hands off between threads, ThreadLocal is the wrong container: the cookie then belongs in whatever object already represents the conversation. Registering the handler JAX-WS lets handlers be declared in an external XML file: XML <?xml version="1.0" encoding="UTF-8"?> <handler-chains xmlns="http://java.sun.com/xml/ns/javaee"> <handler-chain> <handler> <handler-class>com.company.cc.handler.SessionCookieHandler</handler-class> </handler> </handler-chain> </handler-chains> The file sits in the same package as the generated service class, since the annotation resolves relative to that class: Java @WebServiceClient( name = "check", targetNamespace = "http://ws.example.com/", wsdlLocation = "META-INF/wsdl/spellingCheck.wsdl" ) @HandlerChain(file = "sessionCookieHandler.xml") public class Check extends Service { } Every proxy from that service now runs through the handler. One caveat: regenerating from an updated WSDL overwrites the service class and removes the annotation, so keep it in a small subclass or script the regeneration step. Edge Cases Cookie rotation needs no special handling: capture runs on every inbound response, so a new cookie mid-workflow replaces the old value on the next exchange. Expiry is different: a ThreadLocal cannot know when the server-side session times out, so an idle workflow keeps attaching a dead cookie. That fix belongs to the workflow level: catch the session-expired response and re-authenticate. Testing It Without a Container A test can build a stub message context, inject HTTP_RESPONSE_HEADERS, run handleMessage, and check the Cookie header on the next outbound call. Cover the cases that burned earlier versions: two Set-Cookie values in one response, a header name in unexpected case, a pre-existing request map that must survive the copy, and the remove() at the end of the workflow. For integration confidence, run the real client against a stub endpoint that returns Set-Cookie on the first call and asserts the Cookie header on the second. The Takeaway JAX-WS has a session mechanism. It is scoped to a proxy instance, implemented differently across runtimes, and backed by a JVM-wide singleton that does not fit a server-side client handling concurrent users. A custom SOAP handler replaces it with a small class you own, an explicit scope you choose, and behavior identical wherever the application deploys. For teams maintaining legacy SOAP integrations that will not be modernized soon, that trade is usually the right one.
Every app that accepts photo uploads meets HEIC sooner or later. iPhones save in it by default. Neither Java nor Rust can read it out of the box, and the usual answer, libheif, is a C library: native packages in every container image, a C toolchain in the build, and a parser written in C reading files that strangers upload. I had the problem twice, in a Java product and in a Rust one. So I went the other way: decoders written in the language itself, built and improved by AI coding agents, with me steering. Here is how it went. 1. Make It Work, In Each Project One agent per codebase, each starting from an existing open-source decoder in its own language: Openize.HEIC for Java, HEIC decoder for Rust. The first versions lived inside each app. They read the photos, and that was enough to ship. They were ready in no time, given there were upstream libraries to start from, even if some features had to be added to match libheif. It was tempting to stop there. Nobody complains about an upload that works. 2. Extract and Iterate Next, I had each decoder pulled out as a standalone library, open source, with its own tests and releases, aligned with the best practices for each language (and mine). Then I asked each agent to iterate on its own: measure, improve, measure again. That alone went a long way. The Java decoder went from 19 seconds to 3.2 for our ten test photos. 3. Compare Everything With Everything Working alone, each agent eventually ran out of obvious ideas. What changed the game was putting both decoders next to libheif on the same machine with the same photos, and then comparing them stage by stage. Every gap became a lead. If another implementation did a step fast, there was a way to do it even faster, and the size of the gap told me whether it was worth chasing. A gap is a hint with a number attached. The comparison also kept us honest. It showed where we were ahead, and it showed that part of libheif's lead came from doing less work: it copied color samples where our decoder interpolated them. 4. Make the Agents Talk Here is the part that led to further improvements. Each agent, working in its own session, was told to talk with the other agent. I had the Rust agent brief the Java agent on what it had found, and the other way around. A gap one side had already closed became a recipe for the other. The Java decoder took the Rust decoder's entropy decoding approach; the Rust decoder took the Java decoder's parallel tiles and transform tricks. Later, the two agents, who were then aware of each other, even coordinated on their own, communicating which CPU cores each could benchmark on. Connecting them was the most useful step in the project. 5. Repeat On the Gaps That Remain Then we ran the same loop again: compare, find the largest remaining gap, close it, then measure. One more round on the Rust side closed the last single-core gap with libheif. The Java side tried the JVM's vector instructions and gained another 9 to 14%. Not every idea survived. The trick the C library is famous for, wide vector instructions, gained almost nothing in Rust: its slow parts were elsewhere. We measured it, wrote it down, and dropped it. Be Strict About Evidence A computer is never idle. Browsers, chat apps, other agents: everything competes for the CPU, and the numbers move with it. When we measured the very same code twice, back to back, the second run came out about 0.4% slower. Noise with a direction looks exactly like progress, or like a regression. So I asked for proof, not impressions: count CPU work instead of wall-clock time, run old and new in alternating order, split results by type of photo, and drop any "gain" smaller than the noise. Several changes didn't make it. One that looked good overall turned out to slow down rotated photos, which are most of what phones upload, until the agent found why. Where They Stand Today Measured together on the same machine, the same ten photos, all three doing the same work: 8 cores: Rust 0.46 s, Java 0.55 s, libheif 0.81 s1 core: Rust 1.38 s, libheif 1.45 s, Java 1.96 sRust can also interpolate color for sharper edges and still matches libheif: 1.45 s Memory is on par with libheif or below, and a long way from where the two decoders started. What I Take Away Iterating alone gets you far. Comparing gets you further. The gap between two implementations is the best to-do list.Cross-pollinating agents helps a lot. The ideas were there, in two separate sessions. Making them talk to each other triggered more optimizations.Be strict about evidence. Ask for measurements that hold up against noise, and be ready to throw away a change that doesn't.Two implementations in two languages beat one. Each made the other faster. Getting a third as reference (libheif) helped even more.Java is fast, too. “Java is slow” is a meme, not a measurement. Optimized the right way, it comes close to the C library on one core and beats it on eight. Both decoders are open source: Rust: github.com/Valuya/heic-decoder-rustJava: github.com/Valuya/openize-heic-java
Introduction In 2020, while working at Priceline, I created a specialized open-source in-memory database. Designing and implementing took four months. Years later, AI helped me create a TypeScript version in a single day. But what made a single-day rewrite possible was not just AI. A structured design doc, hundreds of unit and behavior tests, and a well-reviewed and published algorithm made that possible. In short, AI is a super tool if used correctly, with the right ingredients. The Java library still exists and is still supported. The goal was not to replace it, but to make the same capabilities available to browser and Node.js developers. This article describes the workflow I would reuse on any similar project, and the mistakes that are easy to make when an AI writes most of the code. Fig-1. The TypeScript version reused the engineering investment. These are different scopes of work, not a speedup ratio. What Is Kiara DB? Kiara DB is an in-memory database optimized for read-heavy scenarios that empowers users to search by any combination of fields or attributes without having to create any special index. Simply load the database and search using any attribute with typo forgiveness — no fine-tuning or index creation needed to obtain high-read performance. The algorithm is based on my 2020 research paper published in the Journal of Algorithms and Computation (JAC). The TypeScript version brings the same capabilities to browsers and Node.js, with zero runtime dependencies. You don't need to know Kiara DB to follow along. Substitute any library or service you want to make available in another language. 1. Start by Converting Behavior Tests The most valuable thing I had going into the migration was not the Java source. It was the test suite. There are two kinds of tests in most projects, and they translate very differently: Behavior and integration tests treat the system as a black box by defining how a system should behave. Those tests are language agnostic and carry over directly.Implementation-focused unit tests depend heavily on the implementation, its underlying platform and the patterns and feature available in the authoring language. These tests translate poorly or maybe not at all. Converting the behavior tests first gave the AI a precise, executable definition of "done." From there, the rest of the migration had one job: make those tests pass. Example. A Java test: Java List<Condition> conditions = new LinkedList<>(); conditions.add(new Condition("country", Operator.EQUAL, "US")); conditions.add(new Condition("state", Operator.EQUAL, "FL")); List<Airport> result = storeSearch.query(airportStore, conditions); assertEquals(3, result.size()); And its TypeScript counterpart: TypeScript const result = store.search([ { field: "country", operator: Operator.EQUAL, values: ["US"] }, { field: "state", operator: Operator.EQUAL, values: ["FL"] }, ]); expect(result).toHaveLength(3); The setup and syntax changed. The expected answer did not. That is the property you want to protect. Make the Tests Trustworthy Before Writing Code A few rules made this step reliable: Pin the source version. Record the exact commit the tests come from. A moving branch is not a stable specification.Run the original tests first. Review and fix any inconsistencies, because if there are any issues, this is a good time to fix them before we copy over unwanted errors to the new repo.Translate the tests using AI with a human review. During translation, maintain a level of isolation. AI model should only see the tests in the source language and not the main application code. The instructions should define the main goal as a test translation without thinking about application code. This prevents AI from bending corners in tests if the application’s code translation in some parts becomes challenging. AI models are very creative in hacking through to meet their goals and then covering their tracks.Cover the edges. Include invalid input, empty values, nulls, duplicates, and boundary values, not just successful queries.Lock the expectations. An expected result changes only through a reviewed decision. The AI may never edit an assertion just to make its code pass. At the end, all 448 Java tests were translated to TypeScript tests. In the next phase of code translation, these immutable tests would be used to verify every changed iteration. Fig-2. Shared fixtures provide a stable contract. A second model's agreement is not a substitute for source-derived expected results. 2. Define Clear Responsibilities for Every Agent If we simply ask an agent to translate the code to another language, the agent will try to take the shortest path and may produce code that, although it passes behavior tests, creates application code riddled with unstable patches, broken algorithms that adversely affect performance, missed features, etc. Careful planning matters; the devil is in the details. Breaking down a bigger task into several agents (with clear responsibilities and how they interact with each other in a loop) gave us the results we hoped for. Agent #1: The Code Analyzer Job: Examine codebase structures to define project specifications. Produces: A requirements inventory with references back to the source: Functional requirements, in the format of request-response, input normalization, error behavior, and result limits.Non-functional requirements, like latency, memory usage, dependencies, and supported runtimes.Any Algorithmic requirements, meaning the translation preserves core data structures and algorithms — for this translation of KiaraDB, this was very important. The last category is the one most often missed. KiaraDB's value comes from its search algorithm. A simple Array.filter() over every record can return the right answers on a small test dataset while losing everything that makes the library useful at scale. Rule: The core algorithm must be translated as is, not replaced. Write idiomatic TypeScript while maintaining core data structures and search methods. Should papers, code, or test outcomes diverge, an automated analyzer mandates human review for resolution of conflict. Agent 2: Planner Job: Turn requirements into small, verifiable steps. Produces: An implementation plan with each step defining the requirements it covers, the tests that prove it is done, and known risks. For example, in the case of KiaraDB, the planner broke down the translation into individual features, implemented separately in sequence. Plain Text Schema and data loading -> structured queries -> collections, ranges, and keyword search -> browser worker support and release checks The planner should also be instructed to scope the work strictly to rewrite and not introduce improvements present in the target language, so new features don't sneak into a code rewrite. Agent 3: Developer Job: Implement one planned step at a time in the target language. Grounded in: Your team's coding policies, for example, strict typing, explicit error handling, no skipped tests, no unrelated refactoring, and documentation of any intentional difference. Language differences show up here. Java can inspect a class's fields at runtime, while TypeScript types disappear after compilation. The TypeScript version therefore offers both explicit schema definitions and decorators that feed the same search engine. That changes how users describe their data, not how queries behave. The developer can propose changing an expected result. However, an agent cannot approve that change; it must coordinate with the other agents we created, who will work together in a loop and bring in a human whenever required Agent 4: Tester and Gap Analyzer Job: Audit both programming projects for structural discrepancies and find missing components Produces: A ranked list of gaps, each with a reproducible example. This agent looks beyond the developer's own tests: requirements with no tests, tests whose expected values came from the AI, changed algorithms, and missing public APIs. A useful gap report is specific, for example: NOT_CONTAINS on a collection field returns 2 rows; Java returns 3. Tests for this use case are missing in both TypeScript and Java. Range queries in TypeScript are significantly slower than the Java version because of an algorithm mismatch. Agent 5: Product Manager Job: Communicate work produced during releases to interested stakeholders. Produces: Public technical notes plus announcement drafts describing working, tested modules. This agent acts like a quality gate for the final product delivery. While producing final artifacts, if it finds that the delivered product doesn’t meet expectations, then it will work with Code analyzer, planner, developer, and tester agents in a loop until the identified gaps are filled. A Reusable Prompt Template Each role works better with a short, explicit brief. Here is the shape I'd reuse: Plain Text Role: Tester and gap analyzer. Inputs: Java repo at <commit>, TypeScript repo, requirements list, latest test results. Task: Find the highest-impact behavior or algorithm gap between the two. Output: One gap with requirement ID, expected vs. actual, and a failing test. Rules: Do not modify implementation code. Do not change expected results. Stop when: One gap is reported, or none is found after checking all requirements. 3. Connect the Agents in a Loop That Knows When to Stop The agents work as a cycle. The analyzer defines goals. The planner chooses sequential moves. The developer builds functions, and the testers verify output consistency. Each gap goes back to the role that can fix it Misunderstood source behavior goes to the analyzer.Missing or mis-ordered work goes to the planner.A bug goes to the developer.A request to accept a difference from Java goes to a human. When everything passes, the product manager prepares the release communication and does a final quality check. Fig-3. Every gap has an owner and every loop has a budget. Running out of budget leads to escalation, not release. Define "Done" Before the Loop Starts The loop needs an exit condition the agents can't negotiate. Mine looked like this: All converted behavior tests pass, including error and edge cases.Secure all high and critical risks.Rewritten algorithm matches the source with no unapproved modifications.Build, type checks, and browser tests pass.Performance and memory meet thresholds agreed on before implementation.Every remaining difference from Java is documented and approved. Track Gaps in One Shared List Rather than forcing agents to repeat the whole project review, every phase maintains one unified tracker. Each entry records the requirement, expected versus actual behavior, a reproducer, severity, owner, and status. Agents report what changed, not everything they know. 4. Avoid Common Mistakes Infinite and Trivial Loops That Burn Tokens While breaking down a big task into multiple agents working together in a loop is essential for success, agents can create endless dialogue without meaningful iterative progress. Therefore, it is essential to keep the agentic loop in check. Set an explicit control policy. I started by capping work at five iterations per batch and reviewing results before approving more. You can use instructions like the following for your main orchestrator agent: Plain Text Work on one planned step at a time. Run at most five implement-and-verify cycles per batch. After each cycle, record what changed and the test result. If two cycles in a row produce no new fix or evidence, stop and escalate. Never skip tests, weaken assertions, or expand scope to claim success. Five is not a magic number. The point is we will allow a human to intervene and check if more iterations are required to achieve the focused goal, instead of going in a loop and burning up tokens. Not Isolating Behavior Tests The agent rewriting the code must never be allowed to rewrite behavior tests to avoid agents tweaking the tests to just pass them. An independent agent who has no knowledge of other agents doing rewrites should first translate the behavior tests and, once done, they should be immutable. Matching Results but Losing the Algorithm A brute force algorithm can pass every test but performs poorly at scale, which is why reviewing and comparing the underlying algorithm must be part of the validation. Treating Runtime Differences as Syntax Some differences between Java and TypeScript look minor but change results: AreaWhat to watch OUT forNumbersJava long values can exceed what a JavaScript number represents exactly. Test large values explicitly.Test dataJSON numbers can lose precision before a test even runs. Store large integers as strings.NullsMissing, null, empty strings, and the text "null" may behave differently. Test each one.Dates and localesPin the time zone and locale. Reject unsupported date formats rather than guessing.ReflectionTypeScript types are erased at runtime. Provide metadata explicitly.Web workersClass instances lose their methods when sent to a worker. Test the actual message boundary. Moving the Goalposts Don't relax a performance threshold because the implementation missed it. Don't relabel a missing feature as optional without approval. Improvements are welcome, but they should be explicit options, not silent changes to how the original behaved. Conclusion The TypeScript transition in a single day was made possible by reusing previous human labor. The published algorithm, along with extensive test history, established the foundation for success. If you have a similar project, here are my suggestions: Convert behavior tests first, with expected results taken from the original system.Split the work into focused agent roles that can't approve their own output.Orchestrate the agents in a loop with guardrails to protect against going into infinite loops.The validation set should include both functional and non-functional requirements, such as automated tests, comparison of source and target algorithms, gap analysis for missing features, etc. The two codebases that we worked on are open source, so you can compare them side by side: Java: github.com/kapoorlabs/kiaraTypeScript: github.com/kapoorlabs/kiara-ts References Kapoor, A. "Efficient Storage and Retrieval of In-Memory Static Data." Journal of Algorithms and Computation.Kiara DB Java repository and the pinned migration baseline.Kiara TS TypeScript repository.Migration plan, parity ledger, and compatibility decisions.TypeScript 5.2 decorator metadata.
When JDK 27 was released on 15 September 2026, most of the attention went to compact object headers and post-quantum TLS. JEP 523 received less coverage, partly because its description sounds like housekeeping: G1 becomes the default garbage collector in all environments. For most applications, that changes nothing. For a specific class of container, it changes the collector silently, with no warning in the logs and no failure at startup. This article covers what the fallback did, which workloads lose it, how to identify affected services, and how to run a comparison that produces usable numbers rather than noise. What the Serial GC Fallback Did G1 has been the nominal default since Java 9. What is less widely known is that HotSpot inspected the machine at startup and overrode that choice in constrained environments. The JVM selected Serial GC when either condition was true: ConditionThresholdAvailable processors1Physical memoryLess than 1,792 MB The reasoning was sound at the time. Serial GC is single-threaded with a very small native memory footprint. On a single-core machine, a concurrent collector spends time competing with application threads for the only available core, and the bookkeeping structures G1 maintains were expensive relative to a small heap. G1 has improved substantially since then. Its native memory footprint has been reduced across several releases, and JDK 26 delivered JEP 522, which removed synchronization overhead from G1's write barriers by introducing a second card table. JEP 523 concludes that work. The fallback is removed, and G1 is now selected in every environment regardless of CPU count or available memory. Serial GC remains fully supported and can still be selected explicitly: Shell java -XX:+UseSerialGC -jar application.jar Applications that already specify a collector, whether G1, ZGC, Parallel, or Shenandoah, are unaffected by this change. Which Workloads Are Affected The change only reaches services that never had an explicit collector flag and that run in a constrained environment. In practice, this describes a predictable set of deployments: Sidecar containers. Log shippers, metrics agents, and service mesh components typically receive a fraction of a CPU and a few hundred megabytes of memory. They are rarely tuned.Batch and queue workers. Short-lived jobs scheduled onto whatever capacity is available.Low-traffic internal services. Admin APIs, configuration services, and internal tooling that are deliberately given small pods.CI runners and development containers. Environments where JVM flags are seldom set because the workload is not production.Pods with fractional CPU limits. This case is easy to miss. A container configured with cpu: 500m may report a single available processor to the JVM, which placed it in Serial GC territory on earlier releases. These are the workloads least likely to appear in a performance test plan, which is precisely why the change deserves deliberate verification. Step 1: Identify Your Current Collector Before changing anything, determine which of your services are actually running Serial GC today. The GarbageCollectorMXBean interface exposes this directly: Java import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; public final class RuntimeFacts { public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); System.out.printf("java version : %s%n", Runtime.version()); System.out.printf("available cpus : %d%n", rt.availableProcessors()); System.out.printf("max heap MB : %,d%n", rt.maxMemory() / (1024 * 1024)); for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { System.out.printf("collector : %s%n", gc.getName()); } } } The collector names identify which implementation is active: CollectorReported MXBean namesSerial GCCopy, MarkSweepCompactG1G1 Young Generation, G1 Concurrent GCParallelPS Scavenge, PS MarkSweepZGCZGC Cycles, ZGC Pauses For a Spring Boot application, registering this as a startup listener puts the information into your existing log aggregation without any additional infrastructure: Java import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.stream.Collectors; @Component public class GcFactsLogger { @EventListener(ApplicationReadyEvent.class) public void logCollector() { Runtime rt = Runtime.getRuntime(); String collectors = ManagementFactory.getGarbageCollectorMXBeans() .stream() .map(GarbageCollectorMXBean::getName) .collect(Collectors.joining(", ")); System.out.printf( "JVM %s | cpus=%d | heap=%,dMB | gc=%s%n", Runtime.version(), rt.availableProcessors(), rt.maxMemory() / (1024 * 1024), collectors); } } Deploy this across your estate, then filter your logs for entries reporting Copy as a collector name. That result set defines the scope of your testing. Step 2: Understand the Native Memory Difference Discussions about garbage collector selection usually center on pause times. For this particular change, native memory consumption is the more consequential metric. G1 maintains bookkeeping structures that Serial GC does not require, including remembered sets, card tables, and per-region metadata. This memory is allocated outside the Java heap, which means it counts against a container memory limit without appearing in heap metrics. Measurements published after the JDK 27 release place G1's native memory overhead at approximately 43 MB, compared with roughly 1.7 MB for Serial GC. Ankur Mundra measured both collectors on Spring Boot 4.1 within real cgroup limits and reported these figures. The absolute difference is modest. The proportional impact depends entirely on container size: Container memory limitApproximate G1 overhead share1024 MB4%512 MB8%256 MB16% On a tightly sized container, this overhead is consumed before the application allocates its first object. Where memory limits were set with minimal headroom, the change alone can produce OOM kills after an upgrade that altered nothing else. Native Memory Tracking provides the per-category breakdown if you want to confirm the figure in your own environment: Shell java -XX:NativeMemoryTracking=summary \ -XX:+UnlockDiagnosticVMOptions \ -jar application.jar Then, against the running process: Shell jcmd <pid> VM.native_memory summary The GC section of the output reports committed native memory attributable to the collector. Step 3: Run a Controlled Comparison A meaningful comparison requires the smallest container size you actually deploy, representative load, and a run long enough to reach steady state. A thirty-second run measures startup behavior rather than collection behavior. Capture GC logs for both configurations: Shell # Pre-Java 27 behaviour java -XX:+UseSerialGC \ -Xlog:gc*:file=serial.log:time,uptime,level,tags \ -jar application.jar # Java 27 default java -Xlog:gc*:file=g1.log:time,uptime,level,tags \ -jar application.jar Three measurements matter, and the third is the one most often omitted: Total pause time. Sum the pause durations across the run rather than comparing individual collections. Serial GC performs fewer, longer pauses; G1 performs more, shorter ones. Only the aggregate is comparable.Tail latency. G1 runs concurrent phases. On a single-core container, those phases contend with request handling for the only available processor. This effect is invisible in a mean and clearly visible at p99.Resident set size under load. This is where the native memory difference becomes operationally relevant. Sample RSS throughout the run rather than reading it once at startup: Shell while true; do ps -o rss= -p "$PID" | awk '{printf "%s %d MB\n", strftime("%H:%M:%S"), $1/1024}' sleep 5 done If RSS approaches your container limit under G1 where it did not under Serial, you have found the problem before it found you. Step 4: Pin the Collector When G1 Loses If measurement shows that G1 performs worse on a constrained workload, the appropriate response is not to defer the JDK upgrade. It is to state the collector explicitly: Shell java -XX:+UseSerialGC -jar application.jar This is a supported configuration. Serial GC is neither deprecated nor scheduled for removal, and JEP 523 explicitly preserves it. In a Kubernetes deployment, express the choice where it will be reviewed: YAML spec: containers: - name: batch-worker env: - name: JAVA_TOOL_OPTIONS value: "-XX:+UseSerialGC" There is an argument for setting the flag explicitly even where G1 performs well. An explicit collector choice is self-documenting. A future engineer reading the manifest can see that a decision was made and tested, rather than inferring what the JVM selected at runtime. Conclusion JEP 523 is a reasonable change. G1 has genuinely closed the gap that justified the fallback, and removing a hidden conditional from the JVM's startup logic simplifies the mental model for everyone. The operational consideration is narrower: a set of small, rarely tested containers will change collectors on upgrade without any signal that it happened. Identifying those containers takes one log statement. Testing them takes one load run. The cost of skipping both is a latency regression or an OOM kill that appears unrelated to any change your team made. Java 27 is not a long-term support release, and many teams will remain on Java 25. That does not remove the relevance of this work. The same default will arrive with the next LTS, and evaluating it on a short-term release carries considerably less risk than discovering it mid-migration. Further Reading JEP 523: Make G1 the Default Garbage Collector in All EnvironmentsJEP 522: G1 GC: Improve Throughput by Reducing SynchronizationJDK 27 Release Notes
GitHub's contribution calendar gives you an already iconic overview of your activity over the year. Each day has a square, and its color changes with the contribution level. And of course, those days and contributions can also be arranged into buildings, with a week becoming a small part of a city and busier weeks adding height to the skyline. I had some spare minutes and built Quarkus Contribution City around this idea, using Java and Quarkus to generate an SVG from GitHub's contribution data. The visual inspiration came from Pink Pixel's skyline, and you can see a version with my real data on my GitHub profile. A scheduled GitHub Action updates the image at night. For a Java developer, this is a small project you can follow from the API request through to the image. You can use the released action on your own profile, then change the drawing code locally once you have a feel for how the city is put together. For this article, I created a special DZone example that adds a small piece of character art above the buildings. Add the City to Your Profile Your GitHub profile README lives in a public repository with the same name as your account. For my account, that repository is myfear/myfear. Open your own profile repository, or create it with a README if you haven't used this GitHub feature before. Copy the project's complete publishing workflow into .github/workflows/contribution-city.yml on the default branch. This example checks out your profile repository and the action's v1 release line. It then generates the image and publishes it to an output branch. The workflow includes the repository write permission needed for that last step. The generation step uses the repository owner's username, so the same configuration can be copied between personal profile repositories. You can add the layout options to that step: - name: Generate contribution city id: city uses: ./.city-action with: github-token: ${{ secrets.CONTRIBUTION_TOKEN || secrets.GITHUB_TOKEN } username: ${{ github.repository_owner } weeks: '53' height: '14' theme: github-dark The local path refers to the action checkout made earlier in the example workflow. The built-in GITHUB_TOKEN is the starting point for reading your visible contribution data. An optional CONTRIBUTION_TOKEN secret can supply a personal token when additional access is needed. The calendar returned by GitHub depends on the token's permissions and your account's contribution visibility settings. After committing the workflow, open Actions in your profile repository, select publish-contribution-city, and choose Run workflow. A successful run creates contribution-city.svg on the output branch. Add this image reference to your profile README, replacing both occurrences of USERNAME:  The example also has a daily schedule for 03:17 UTC. Subsequent runs create a commit when the generated image changes. For this setup, the workflow and its run history can be found in your profile repository, while the Java implementation is maintained in the action's repository. Give Each Week a Building The city is arranged in time order, with the most recent week on the right. Every building is two character cells wide, so all weeks occupy the same horizontal space. Weekly contribution totals determine the height, and daily contribution levels provide the window colors. Month labels beneath the street help you find your place in the year. Height needs a little extra thought. A very busy week can have many times the contributions of a quiet one. With a linear scale, those quieter weeks would be compressed close to the street. The city uses a logarithmic scale, which gives them more room while preserving the order of weekly totals. For each week, the calculation can be expressed as: int height = weeklyTotal == 0 ? 1 : 1 + (int) Math.round( Math.log1p(weeklyTotal) / Math.log1p(maximumWeeklyTotal) * (maxHeight - 1)); With a maximum of 20 contributions and a height limit of 14, a week with three contributions gets seven window rows. The busiest week gets 14, and a week with zero contributions keeps one row. Quiet periods therefore retain their position in the calendar. An antenna marks the busiest displayed week; when totals are tied, the most recent week receives it. The two columns of windows are filled by cycling through the days of the week. This repeats the daily pattern in taller buildings, so window count is a visual texture. The weekly total controls height, while the window colors carry the daily contribution levels. Together, they give you a view of the pattern across your calendar. You can change weeks to 12 for a shorter view. The tallest building is then calculated from those recent weeks, which lets the selected period use the available height. Keep this in mind when comparing images: the same week can appear taller in a shorter view. The displayed contribution total still covers the full calendar returned by GitHub. Follow the Data Through Java The released project uses Quarkus with the Quarkus GitHub Action extension. That extension connects an @Action method to workflow inputs, outputs, and the job summary. Inside the method, the drawing process comes down to three steps: ContributionCalendar calendar = contributionClient.fetch( configuration.username(), inputs.getGitHubToken().orElseThrow(), context.getGithubGraphQLUrl()); Scene scene = cityBuilder.build(calendar, configuration.options()); String svg = svgRenderer.render(scene, configuration.options().theme()); The client reads the contribution calendar with one GraphQL request and converts the response into Java records for the calendar, weeks, and days. CityBuilder uses these records to place roofs, windows, and the street in a grid. SvgRenderer turns that grid into the final SVG. Changes to the skyline can therefore be made in plain Java classes, with the GitHub connection kept in the client. The SVG contains the shapes and text needed to display the city. Adjacent characters with the same color are grouped during rendering, and their horizontal positions are set explicitly to keep the columns aligned. Identical data and options produce identical file contents, which allows the publisher to compare images before creating a commit. The action sets up Java and JBang, builds the selected source revision, and runs the packaged application. Change the Layout Locally To try a change, install JDK 21 and JBang, with Git and Bash available. The repository includes a Maven wrapper. JBang is also used by the integration tests to run the packaged action through the same launcher used in GitHub Actions. git clone --branch v1.0.0 https://github.com/myfear/quarkus-contribution-city.git cd quarkus-contribution-city ./mvnw verify The tests use local test data and a local GraphQL server, so you can run them without GitHub credentials. They also generate SVG previews under target/previews. Open github-dark.svg, recent-12.svg, and empty.svg in a browser to compare a full calendar, a shorter period, and a calendar with zero contributions. Start with the height calculation in CityBuilder, then run the same command again and compare the previews. The saved data stays the same between runs, which makes the effect of your change easier to see. The project is available under the Apache License 2.0, and the v1.0.0 release gives you a fixed starting point. Give the City a DZone Landmark Version 1.0.0 exposes weeks, height, and the two built-in themes through workflow inputs. For a custom shape, you extend the Java code in your fork. The Scene record gives you a grid of cells to change before the SVG is rendered, and that is where we'll add the DZone lettering. Each cell has a character, a role such as roof or window, and the color information used by the renderer. A character mask is enough to describe a new shape: # marks a filled block, and spaces leave the background visible. By arranging those blocks, you can draw letters, an arch, or a stepped tower. For this example, the lettering is placed above the weekly buildings. It has its own fixed shape, while the buildings below continue to show the contribution calendar. The image uses a snapshot of my real account data, with 534 contributions returned by GitHub on October 5, 2026, when I wrote this article. A DZone-inspired palette and decorative lettering added to my contribution city. The weekly building heights and daily window patterns come from the same calendar used by the regular view. Add this class to the existing city package in your fork, at src/main/java/com/themainthread/contributioncity/city/DZoneLandmark.java: package com.themainthread.contributioncity.city; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.themainthread.contributioncity.render.Theme; public final class DZoneLandmark { public static final Theme THEME = new Theme("dzone-example", "#161b22", "#242c36", "#303947", "#f58a42", "#9ba9ba", "#edf2f7", List.of("#536070", "#86431f", "#b85b25", "#e57d36", "#ffb365")); private static final List<String> MASK = List.of( "#### ##### ### # # #####", "# # # # # ## # # ", "# # # # # ## # # ", "# # # # # # # # #### ", "# # # # # # ## # ", "# # # # # # ## # ", "#### ##### ### # # #####"); private DZoneLandmark() { } public static Scene addTo(Scene city) { int landmarkWidth = MASK.getFirst().length() * 2; int width = Math.max(city.width(), landmarkWidth); int left = (width - landmarkWidth) / 2; List<List<Cell>> rows = new ArrayList<>(); Cell block = new Cell('█', CellKind.ROOF, 0, -1); for (String line : MASK) { List<Cell> row = new ArrayList<>(Collections.nCopies(width, Cell.SKY)); for (int column = 0; column < line.length(); column++) { if (line.charAt(column) == '#') { row.set(left + column * 2, block); row.set(left + column * 2 + 1, block); } } rows.add(row); } rows.add(Collections.nCopies(width, Cell.SKY)); for (List<Cell> sourceRow : city.rows()) { List<Cell> row = new ArrayList<>(sourceRow); row.addAll(Collections.nCopies(width - city.width(), Cell.SKY)); rows.add(row); } return new Scene(city.username(), city.totalContributions(), rows); } } The theme defines the background, two building shades, roof, street, and label colors, followed by the five window colors. Those window colors follow GitHub's contribution levels from zero through four. Here, the roof color is also used for the lettering, so the decoration has a consistent orange color across all seven rows. Inside addTo, each marked position is expanded to two cells because the renderer's cells are taller than they are wide. The lettering is centered, a blank row is added beneath it, and the original city rows are copied below. Short calendars receive extra background space on the right to make room for the lettering. The dates, counts, and order of the weekly buildings are preserved. To use the decoration in your fork, import DZoneLandmark from the city package in ContributionCityAction. Replace the existing scene-building and rendering lines with: Scene scene = cityBuilder.build(calendar, configuration.options()); Scene decorated = DZoneLandmark.addTo(scene); String svg = svgRenderer.render(decorated, DZoneLandmark.THEME); This selects the example's palette in Java. The published @v1 action continues to accept github-dark and mono; your fork contains the additional drawing code. For a local preview, add the following after the existing Files.writeString call in PreviewTest.write, with the same import for DZoneLandmark: Scene decorated = DZoneLandmark.addTo(builder.build(calendar, options)); Files.writeString(directory.resolve(name.replace(".svg", "-dzone.svg")), renderer.render(decorated, DZoneLandmark.THEME)); Run ./mvnw verify again and open target/previews/github-dark-dzone.svg. The build also writes the shorter and empty versions with the -dzone.svg suffix, so you can check how the decoration fits several calendars. When you're ready to use your fork on GitHub, update the second checkout in the publishing workflow to your fork's repository and a commit containing your changes. The generation step then runs the customized action from that checkout. Try It With Your Own Contributions Try Quarkus Contribution City with your own GitHub account and add the generated SVG to your profile. Start with the released action, then fork the project and change the character mask to give your city a landmark of its own. You could draw a stepped tower from your hometown or add your team's initials above the street, using the DZone version as a starting point. Share your version in a GitHub issue, or open a pull request if you'd like to contribute a new shape.
If you have worked on a mature Java backend application, your src/main/resources/db/migration folder probably looks like a chaotic history ledger: Plain Text V1__init_schema.sql V2__add_users_table.sql ... V142__add_status_column.sql V143__fix_status_typo.sql V144__drop_old_status.sql V145__add_missing_index.sql Tools like Flyway and Liquibase have been the industry standard for over a decade. They operate on an imperative model: “Apply this exact sequence of scripts to transition the database from version N to version N+1.” In the early stages of a project, this model feels logical. But at scale, imperative migrations create severe operational friction. Two engineers branching off main will inevitably create conflicting V146__... scripts. Standing up a new test environment from scratch requires replaying hundreds of sequential scripts. Most dangerously, if an engineer accidentally commits a script containing an unsafe DROP TABLE or ALTER COLUMN, the migration tool will blindly execute it against the production database, potentially causing catastrophic data loss. Modern infrastructure tooling—such as Kubernetes and Terraform—moved away from imperative scripts years ago. They utilize declarative state reconciliation: “Here is exactly what the system should look like right now. Figure out how to make it so, safely.” It is time we manage relational database schemas with that same declarative philosophy. Enter SchemaSynchronizer SchemaSynchronizer is an open-source library for Java and Spring Boot that brings declarative, desired-state schema evolution to relational databases (PostgreSQL, MySQL, MariaDB, SQL Server, and Oracle). Instead of maintaining a perpetually growing chain of migration scripts, your application maintains a single schema-definition.json file representing the current, desired state of your database structure. JSON { "formatVersion": 2, "dialect": "postgresql", "tables": { "work_items": { "createSql": "CREATE TABLE IF NOT EXISTS work_items (id UUID PRIMARY KEY, status VARCHAR(32))", "columns": [ {"name": "id", "definition": "UUID NOT NULL"}, {"name": "status", "definition": "VARCHAR(32)"} ], "indexes": [ "CREATE INDEX IF NOT EXISTS idx_work_items_status ON work_items (status)" ] } }, "changes": [] } On startup, SchemaSynchronizer does not just blindly execute SQL. It executes a state-reconciliation loop. How the Synchronization Engine Works Under the Hood When your Spring Boot application boots, SchemaSynchronizer connects to the database via JDBC and extracts the live catalog metadata. It inspects existing tables, column types, default values, nullability constraints, and indexes. It then computes a diff against your JSON definition and applies changes based on dialect-specific rules. Database engines are notoriously fragmented in how they handle Data Definition Language (DDL). Transactional DDL: On PostgreSQL and SQL Server, SchemaSynchronizer wraps the synchronization process in a transaction. If something fails, the entire schema change is rolled back cleanly.Implicit Commits: MySQL, MariaDB, and Oracle natively commit open transactions the moment a DDL statement is executed. SchemaSynchronizer adjusts its execution strategy for these dialects, relying on granular verification checks rather than transaction rollbacks.Distributed Locking: To prevent multiple application instances from fighting over the schema during a rolling deployment, the library utilizes native distributed lock primitives (pg_try_advisory_xact_lock in Postgres, sp_getapplock in SQL Server, GET_LOCK in MySQL, and DBMS_LOCK in Oracle). The Safety Boundary: Fail-Closed Design The most critical architectural requirement for automated database tooling is preventing accidental data destruction. SchemaSynchronizer is built around a strict, fail-closed safety boundary. It divides schema evolution into two distinct categories: 1. Safe Additive Changes (Automated) If you add a nullable description column to your JSON definition, SchemaSynchronizer detects the missing column and issues the ALTER TABLE ... ADD COLUMN statement automatically on startup. The same applies to creating new tables, creating indexes, widening compatible data types (e.g., VARCHAR(50) to VARCHAR(100)), or relaxing NOT NULL constraints. 2. Destructive or Ambiguous Changes (Manual Review) What happens if you delete a column from the JSON definition? SchemaSynchronizer never infers a DROP operation. If it detects an orphaned live column, or a type narrowing that could truncate data, it halts the synchronization process and outputs the exact SQL required to resolve the difference. Plain Text [SchemaSynchronizer] Destructive difference detected. Manual review required: ALTER TABLE work_items DROP COLUMN old_status; This enforces a hard operational boundary. Routine additive drift is repaired automatically, reducing developer friction, but destructive reconciliation always requires explicit human intervention and approval. Handling Complex Migrations With Checksummed Ledgers Not every database operation can be cleanly inferred from a declarative table structure. Operations that carry specific business logic — such as data backfills, complex CHECK constraints, triggers, or specific user grants — require explicit execution. To handle these, SchemaSynchronizer includes an ordered changes array within the JSON document. These act as an immutable, checksummed ledger, similar to traditional migrations, but with a critical addition: Verification SQL. JSON "changes": [ { "id": "001-work-item-status", "description": "Backfill and constrain work item status", "statements": [ "UPDATE work_items SET status = 'PENDING' WHERE status IS NULL", "ALTER TABLE work_items ALTER COLUMN status SET NOT NULL" ], "verificationSql": "SELECT NOT EXISTS (SELECT 1 FROM work_items WHERE status IS NULL)", "phase": "AFTER_SCHEMA" } ] The verificationSql must be a read-only query that returns a boolean true. This ensures idempotency. If the database already satisfies the verification query (perhaps because a DBA manually applied the fix during an incident), SchemaSynchronizer records the change set as completed without attempting to blindly replay the UPDATE statements. Implementation: Spring Boot and CLI SchemaSynchronizer integrates natively into Java applications. For Spring Boot, add the dependency to your build file: Maven: XML <dependency> <groupId>com.thinkaillc</groupId> <artifactId>schema-synchronizer</artifactId> <version>2.0.0</version> </dependency> Configure your application.properties to enable the initializer and tell Hibernate to back off and only validate the schema: Properties files schema-synchronizer.enabled=true schema-synchronizer.schema=public schema-synchronizer.fail-on-pending=true # Let SchemaSynchronizer handle DDL; tell Hibernate to just validate spring.jpa.hibernate.ddl-auto=validate The Standalone CLI Pipeline Many organizations prefer to decouple schema migrations from application startup, executing them directly from a CI/CD pipeline (like GitHub Actions or Jenkins). SchemaSynchronizer ships a standalone executable JAR bundling the JDBC drivers for all supported engines. You can dry-run a deployment against a target database to see exactly what would change, without committing any DDL: Shell export SCHEMA_DB_PASSWORD='target-password' java -jar schema-synchronizer-cli-2.0.0-standalone.jar dry-run \ jdbc:postgresql://localhost:5432/target_app app_user - \ schema-definition.json public schema_synchronizer_history Ready to Drop the Migration Scripts? Imperative migration scripts served the Java ecosystem well for years, but as our deployment topologies grow more complex, managing hundreds of linear state-transition files becomes a liability. By adopting a declarative approach, you can eliminate merge conflicts on migration files, instantly stand up new environments from a single source of truth, and enforce a strict safety boundary that prevents automated tooling from ever dropping production data. Check out the architecture, dialect support, and Quick Start guides on the repository: GitHub: eugenena/SchemaSynchronizer
The message left the first service at 2:14 PM and never reached the last one. Between those facts: four pipeline stages, six topics, a pub/sub API moving every record. The engineer on call had Kafdrop open, the offsets looked fine, and nobody could say which stage had eaten the record. That gap is why we built message search for Kafdrop at a hackathon. The setup was familiar from my day job: a platform moving data between pipeline stages over a pub/sub API, with no way to ask where a message went when something breaks. Kafdrop showed partitions and offsets. It couldn't search inside the messages. Kafka has no index. That is the whole problem in one sentence. A topic is an append-only log split across partitions, and the consumer API reads by offset: hand it 41,207, and it returns record 41,207. There is no "find the record containing order-88412." To search, you pick a starting point and read forward until you find what you want or stop. So that is what our feature does, with guardrails that keep the search from hurting the cluster. The interesting part was the caps, the consumer setup, and the SRE agreement. Why a Full Scan Is Not an Option The obvious approach is to read the whole topic and grep. Topics hold days of data, so the whole thing doesn't fit in memory. Reading every record on every search hammers the brokers, and during an incident that is the worst time to add load. Most searches end with a few matches, so nearly all of that work is wasted. The other approach is to mirror every topic into a search engine. That works, and plenty of teams do it. It also means running a second distributed system and explaining index lag during every incident. For a hackathon debugging tool, that was too much machinery. The Design: Seek, Scan, and Stop The feature takes four inputs: a topic, a query string, a start time, and two caps. The start time bounds how far back the search goes. Kafka's offsetsForTimes maps a timestamp to the first offset at or after it per partition, or null when the partition holds nothing that new. The user picks "the last hour" or "since the deploy." The result cap bounds memory: return the first N matches and stop. Debugging usually needs one record, not ten thousand. The scan cap bounds broker load: stop after M records even with no match. Every search becomes a fixed amount of work, whatever the user types. A typo costs M reads. The scan can never grow beyond that. Polls use bounded batches, so the tool never holds more than one page of records at a time. Nothing loads a whole topic. Safety: Assign, Don't Subscribe The consumer setup is where a search tool can quietly cause damage. Three decisions were non-negotiable. First, the search consumer uses assign, not subscribe. Subscribe joins a consumer group, bringing coordination and rebalances. A debugging tool has no business in any of that. Assign hands the consumer a fixed partition list and stays out of group coordination entirely. Second, the consumer never commits offsets. Auto-commit is off, and the code never calls commit. The default config commits automatically, so this is the one that bites: a search tool that advances a production group's offsets is a horror story, and the fix is one config line. Third, the scan cap doubles as a safety control: every search reads at most M records, a worst case SRE can read before approving. The Search Loop Here is the core in Java. The three constants are the whole design: matches to return, records to read in the worst case, records per poll. The values are illustrative; tune them to your topics. Java private static final int RESULT_CAP = 25; private static final int SCAN_CAP = 50_000; private static final int POLL_BATCH = 500; public List<FoundMessage> search(String topic, String query, long startTimeMs) { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, String.valueOf(POLL_BATCH)); List<FoundMessage> matches = new ArrayList<>(); try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) { List<TopicPartition> partitions = new ArrayList<>(); for (PartitionInfo p : consumer.partitionsFor(topic)) { partitions.add(new TopicPartition(topic, p.partition())); } consumer.assign(partitions); Map<TopicPartition, Long> times = new HashMap<>(); for (TopicPartition tp : partitions) times.put(tp, startTimeMs); for (Map.Entry<TopicPartition, OffsetAndTimestamp> e : consumer.offsetsForTimes(times).entrySet()) { if (e.getValue() != null) consumer.seek(e.getKey(), e.getValue().offset()); else consumer.seekToEnd(Collections.singletonList(e.getKey())); } long scanned = 0; while (scanned < SCAN_CAP && matches.size() < RESULT_CAP) { ConsumerRecords<String, String> batch = consumer.poll(Duration.ofMillis(500)); if (batch.isEmpty()) break; for (ConsumerRecord<String, String> r : batch) { if (++scanned > SCAN_CAP) break; if (r.value() != null && r.value().contains(query)) { matches.add(new FoundMessage(r.topic(), r.partition(), r.offset(), r.timestamp(), r.value())); if (matches.size() >= RESULT_CAP) break; } } } } return matches; } From the top: the config disables auto-commit and fixes the poll batch size. Assign takes a fixed partition list. offsetsForTimes turns the start time into a starting offset per partition; the null branch seeks to the end for partitions with nothing that new. The loop reads forward and stops at whichever cap hits first. Nothing commits, and try-with-resources closes the consumer. Matching is a substring check on the record value. Tombstones carry nulls, so the null check is load-bearing. Shipping It: A Container, Kubernetes, and the SRE Agreement The app ships as a container image: the search service and its config, nothing else. It runs on Kubernetes as a small deployment with tight resource limits, since the result cap already bounds memory. One replica is plenty. YAML apiVersion: apps/v1 kind: Deployment metadata: name: kafdrop-search spec: replicas: 1 selector: matchLabels: app: kafdrop-search template: metadata: labels: app: kafdrop-search spec: containers: - name: search image: registry.example.com/kafdrop-search:1.0.0 resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" env: - name: KAFKA_BROKERS value: "kafka:9092" The manifest is deliberately boring: one replica, tight memory limits, brokers passed as config. The SRE conversation was short, because the design answered their questions first. The tool only reads: assign instead of subscribe, no offset commits, read-only Kafka credentials. Every search is bounded by the scan cap, so the worst case was a number everyone could read. That agreement mattered more than the code. The caps were the trust. A Debugging Routine That Works First, search the topic for the message using something unique: an order ID, a request ID. Found it? Note the offset and timestamp. Second, check consumer group lag for the downstream stage. If the group consumed past your message's offset, the stage read it, and the problem is in the consumer's logic. If lag is stuck or growing, the consumer is behind, crashed, or wedged on a poison record. Third, look at the consumer: logs around the message's timestamp, error handling, the dead-letter path. The order matters. It separates "the message never arrived" from "the message arrived and something went wrong." Before, step one was guesswork. Now it takes minutes. What We Kept Kafka gives you ordering and durability, not search. Bolting search onto an append-only log means accepting the scan. Make it bounded and boring: seek to a timestamp, read forward in small batches, stop at the first cap. Keep the three decisions that made it safe. Assign instead of subscribe, so the tool never joins a consumer group. Never commit offsets, so reading changes nothing. A scan cap that turns every search into a known quantity of broker work. Get those right, and SRE will let you run it against production. Get them wrong, and you have built a very efficient way to cause your next incident. After the hackathon, the team kept the tool for one job: finding where a message stopped. A search, a lag check, and a look at the consumer, done in minutes. Diagnosis time during incidents fell.
Developer Strategist,
IBM Research
Software Craftsman
Award-winning Software Engineer and Architect,
OS Expert
Senior Principal Developer Advocate,
IBM