RedStack
https://redstack.dev
Microservices, Cloud Native and AIThu, 15 Oct 2026 16:30:17 +0000en-US
hourly
1 https://s0.wp.com/i/webclip.pngRedStack
https://redstack.dev
32324033274What the Go and Java Benchmark Really Says About Choosing a Runtime
https://redstack.dev/2026/11/05/what-the-go-and-java-benchmark-really-says-about-choosing-a-runtime/
https://redstack.dev/2026/11/05/what-the-go-and-java-benchmark-really-says-about-choosing-a-runtime/#respondThu, 05 Nov 2026 17:32:00 +0000https://redstack.dev/?p=4917Continue reading →]]>Key Takeaways
Article 9 supports runtime choices by decision criterion, not by language identity. Peak throughput, pooled fixed-rate response time, near-limit p95/p99, resident memory, CPU per 1,000 RPS, and Java GC evidence point to different tradeoffs.
Under Article 9’s documented single-service-host Linux HTTP benchmark setup, peak throughput and near-limit 95pct-go-peak p95/p99 favored the measured Java Helidon SE oracle-jdk-26-jvm and oracle-jdk-26-aot configurations.
Go net/http had the strongest evidence in Article 9’s pooled fixed-offered-rate response-time view and measured resident memory footprint view.
Treat oracle-jdk-26-aot as the benchmark’s measured Oracle JDK configuration with that label. It was not a GraalVM Native Image executable, and it is not a universal Java AOT, Project Leyden, startup, footprint, or steady-state throughput conclusion.
You have the benchmark results now. Article 9 reported results for a compact Go net/http service and a Helidon SE Java service running on two measured Oracle JDK runtime shapes.
So the question becomes the one teams actually ask in architecture reviews:
Which runtime should we choose?
That sounds like a request for one answer. It is not. A runtime decision is a workload decision, and the workload in this series is intentionally narrow: a single-service-host Linux HTTP benchmark with controlled fixtures, fixed-rate comparisons, near-limit comparisons, RSS measurements, CPU normalization, and Java GC pause evidence.
It is not a production microservices simulation. It does not include database execution, vector search latency, model inference, TLS, request logging, Kubernetes, autoscaling, service mesh behavior, or multi-node deployment.
That narrowness is what makes the benchmark useful. We can say concrete things about this service shape without pretending those things automatically apply to every service your team might operate.
This final article translates Article 9’s published results into runtime-selection guidance. It does not add a new benchmark run or introduce a new metric table. It answers the practical question: given the reported results, which runtime shape is attractive for which decision criterion, and where should we stop generalizing?
Start with the decision this benchmark can help with
Article 9 helps when your service resembles the benchmark: compact, HTTP-based, single-service-host, and affected enough by local runtime behavior that the runtime choice matters.
Imagine you are building a small service tier in front of an AI application path. The service validates JSON, does a small amount of deterministic local work, maybe prepares a call to a database or embedding service, and returns a compact response.
You are not trying to benchmark the database yet. You are trying to decide whether the local HTTP service boundary should start as Go net/http or Java Helidon SE on the measured Oracle JDK runtime shapes.
That is the kind of decision Article 9 can inform. It gives you evidence about local HTTP request handling, runtime scheduling, serialization, CPU use, memory footprint, and response-time behavior under the documented benchmark setup.
It does not answer the full production question for a service that spends most of its time waiting on a database, cache, queue, remote API, model endpoint, TLS stack, logging pipeline, tracing agent, or service mesh. Those are real service costs. They just were not part of this benchmark’s primary result.
The right way to read Article 9 is therefore not:
Which language won?
The better question is:
Which measured runtime shape best fits the constraint I care about for this service boundary?
That wording matters. A peak-throughput decision is different from a memory-density decision. A pooled fixed-rate response-time decision is different from a near-limit p95/p99 decision. A Java ecosystem and diagnostics decision is different from a narrow RSS decision.
All runtime recommendations in this article depend on Article 9’s published result tables and runtime manifest. The labels go-http, oracle-jdk-26-jvm, and oracle-jdk-26-aot refer only to those measured configurations under the documented single-service-host Linux HTTP benchmark setup.
Keep the runtime labels attached to the measured shapes
A runtime shape is the measured combination of application implementation, runtime, configuration, operating environment, and benchmark setup.
Article 9 compared three runtime labels:
go-http: the measured Go net/http service shape.
oracle-jdk-26-jvm: the measured Helidon SE service configuration on the documented Oracle JDK 26 JVM-shaped runtime.
oracle-jdk-26-aot: the measured Helidon SE service configuration on the documented Oracle JDK 26 AOT-labeled runtime configuration.
Use Article 9’s runtime manifest and result tables as the source of truth for the exact JDK build, flags, operating system, CPU shapes, packaging, offered-rate basis, and measured cells behind those labels.
Those labels are shorthand for measured configurations. They are not standalone claims about every Go, Java, Helidon, OpenJDK, or Oracle JDK deployment. The Java labels refer to the Oracle JDK 26 builds and runtime configurations used in Article 9. They should not be read as results for every OpenJDK distribution, every vendor build, or every Java runtime.
That distinction is especially important for oracle-jdk-26-aot. In this article, oracle-jdk-26-aot means only the Article 9 configuration labeled that way in the public runtime manifest. The label does not mean a GraalVM Native Image executable. It refers only to the Oracle JDK runtime configuration documented for this benchmark, and it should not be read as a general Project Leyden result or as a claim about all Java AOT techniques.
Read each Article 9 view as a different decision lens
Each Article 9 result view answers a different runtime-selection question. Keep the recommendation attached to the view it came from.
Peak throughput
What Article 9 measured: Which measured runtime shape led each displayed fixture and CPU-shape peak cell
How to use it: Use this when throughput headroom is the primary constraint
Pooled fixed-offered-rate response time
What Article 9 measured: Pooled p50, p95, p99, and mean response time across Article 9’s fixed-rate records
How to use it: Use this as an aggregate response-time view under the documented load-generation method, not as a per-cell guarantee
Near-limit p95/p99
What Article 9 measured: Response time at the 95pct-go-peak offered-rate basis
How to use it: Use this when high-load tail behavior near the Go-derived comparison point is the main concern
RSS and RSS per 1,000 RPS
What Article 9 measured: Measured service resident memory footprint, both raw and normalized
How to use it: Use this when memory density is a first-order platform constraint
CPU per 1,000 RPS
What Article 9 measured: CPU use normalized by throughput for measured near-limit rows
How to use it: Use this per matching fixture and CPU-shape cell, not as a runtime-wide ranking
Java GC pause evidence
What Article 9 measured: Java-only GC pause data for the measured Java shapes
How to use it: Use this as Java runtime-burden context, not as a symmetric Go-versus-Java counter comparison
Read all response-time claims under Article 9’s documented load-generation and latency-recording method. Fixed offered rate by itself should not be treated as proof that coordinated omission was eliminated; the interpretation depends on the complete measurement method used in Article 9.
Where this article says “median p95” or “median p99,” it means Article 9’s median across repeated measurements of the p95 or p99 response-time statistic for that cell.
The practical rule is simple: do not collapse these views into one “winner.” Choose the metric that matches the decision you need to make.
Choose by decision criterion, not by language identity
The compact interpretation of Article 9 is this: Java was stronger for peak-throughput and near-limit p95/p99 evidence, while Go was stronger for pooled fixed-rate response time and resident memory evidence.
Peak-throughput envelope
Article 9’s result points first to…: Java Helidon SE on the measured Oracle JDK shapes
Why: In Article 9’s published peak-throughput table, the measured Java shapes led the displayed peak cells: oracle-jdk-26-jvm led six of nine cells and oracle-jdk-26-aot led three
Pooled fixed-offered-rate response time
Article 9’s result points first to…: Go net/http
Why: Go had the lowest pooled p50, p95, p99, and mean values under Article 9’s documented load-generation method
Near-limit p95/p99 at 95pct-go-peak
Article 9’s result points first to…: Java Helidon SE on the measured Oracle JDK shapes
Why: Both measured Java runtime shapes had lower median p95 and p99 values than Go in the displayed cells
Resident memory footprint
Article 9’s result points first to…: Go net/http
Why: In Article 9’s displayed near-limit rows, Go had lower measured service RSS than both measured Java shapes
CPU per 1,000 RPS
Article 9’s result points first to…: No single runtime-wide default
Why: CPU per 1,000 RPS varied by fixture and CPU shape
Java runtime-burden analysis
Article 9’s result points first to…: Compare the two measured Java shapes
Why: Java GC pause evidence helps explain Java runtime behavior, but it is not a complete latency explanation
For peak-throughput envelope, Article 9 favored the measured Java runtime shapes. In the published peak-throughput table, oracle-jdk-26-jvm led six of nine displayed fixture and CPU-shape peak cells, and oracle-jdk-26-aot led three. Treat that as a result for the displayed cells, not as a general Java-over-Go claim.
For pooled fixed-offered-rate response time, Article 9 favored Go. In that pooled view, Go had the lowest p50, p95, p99, and mean response-time values. This should not be read as a per-cell guarantee for every fixture and CPU shape.
For near-limit p95 and p99, Article 9 favored the measured Java runtime shapes. At Article 9’s 95pct-go-peak offered-rate basis — an offered rate tied to Go’s measured peak for the matching fixture and CPU-shape cell — both measured Java runtime shapes had lower median p95 and p99 values than Go in the displayed cells.
For resident memory footprint, Article 9 favored Go. In the displayed near-limit rows, Go had lower measured service RSS than both measured Java runtime shapes, both raw and normalized per 1,000 RPS. If memory density is a first-order requirement for a similar compact service, Go has the stronger evidence.
For CPU per 1,000 RPS, Article 9 does not support one runtime-wide ranking. The result varied by fixture and CPU shape. Some Java cells were lower than Go; others were higher. If CPU per unit throughput decides the architecture, read the matching fixture and CPU-shape cell.
For Java GC pause evidence, Article 9 gives useful Java-only context. The evidence varied by Java runtime shape, fixture, and CPU shape. Use it to compare the measured Java runtime shapes, not to explain all response-time behavior or compare symmetrically with Go runtime counters.
That is the core takeaway: the recommendation changes with the metric.
If you need peak-throughput headroom in a service shaped like the benchmark, the measured Java runtime shapes have the stronger evidence. If you need the lowest pooled fixed-rate response-time view or the smallest measured resident memory footprint, Go has the stronger evidence. If you need near-limit p95/p99 behavior at the Go-derived 95pct-go-peak basis, the measured Java runtime shapes have the stronger evidence.
Where Go net/http looked attractive
Go net/http looked strongest in two places that matter to developers and platform engineers: pooled fixed-offered-rate response time and resident memory footprint.
In Article 9’s pooled fixed-offered-rate view, Go had the lowest p50, p95, p99, and mean response-time values. That view aggregates the fixed-rate records and reports response time in milliseconds. Read it as a pooled result under Article 9’s documented load-generation method, not as a guarantee that every individual fixture and CPU-shape cell favored Go.
Go’s memory result was the clearest Go-favoring resource result in Article 9. In the displayed near-limit rows, Go had lower measured service RSS than both measured Java runtime shapes. Article 9 also showed that RSS per 1,000 RPS preserved the same pattern. That matters because memory density is often a first-order platform concern for compact services.
Use the Go result when the service boundary looks like the benchmark: small, direct, and operationally simple. Go net/http is a good early candidate when the team wants a compact runtime surface, the service does not require Java ecosystem continuity, and resident memory density matters.
A practical Go-first rule looks like this:
If the service resembles the benchmark,
and pooled fixed-rate response time or resident memory footprint is the deciding criterion,
and the team does not need Java ecosystem continuity for this boundary,
then start the prototype with Go net/http.
Then add the real dependencies and observability path before making it a platform rule.
That last sentence is the difference between using a benchmark and overusing it. A benchmark can point you to the first runtime to test. It cannot remove the need to measure your representative service.
Where Java Helidon SE on the measured Oracle JDK shapes looked attractive
Java Helidon SE on the measured Oracle JDK shapes looked strongest for peak-throughput envelope and near-limit p95/p99 behavior.
In Article 9’s peak-throughput table, the oracle-jdk-26-jvm shape led six of nine fixture and CPU-shape peak cells, and the oracle-jdk-26-aot shape led the other three. Go did not lead a peak-winner cell in that table. For a compact service shaped like this benchmark, that is a direct and useful result: when peak throughput is the deciding metric, the evidence supports Java Helidon SE on the measured Article 9 Oracle JDK runtime shapes.
Near the Go-derived limit, the Java result was also strong. At Article 9’s 95pct-go-peak offered-rate basis, both measured Java runtime shapes had lower median p95 and p99 response-time values than Go in the displayed fixture and CPU-shape cells.
That does not contradict the pooled fixed-rate response-time result. It tells us the response-time decision depends on the offered-rate basis.
This is a common benchmark trap. A team may quote the pooled fixed-rate table to make one response-time argument, while another team quotes the near-limit table to make a high-load p99 argument. Both may be reading real evidence, but they are answering different questions.
So keep the question attached to the metric:
What had the lowest pooled fixed-offered-rate response-time values?
Article 9 view to use: Pooled fixed-offered-rate p50, p95, p99, and mean
Runtime shape favored in that view: Go net/http
What had lower p95/p99 near the Go-derived offered-rate limit?
Article 9 view to use: 95pct-go-peak near-limit p95/p99
Runtime shape favored in that view: Measured Java Helidon SE runtime shapes
What had the strongest peak-throughput envelope?
Article 9 view to use: Peak-throughput table
Runtime shape favored in that view: Measured Java Helidon SE runtime shapes
Java Helidon SE on the measured Oracle JDK shapes may also be attractive for non-benchmark reasons when operational continuity matters. JVM diagnostics, GC logs, Java Flight Recorder, Java libraries, Helidon SE integration, existing deployment pipelines, and established incident runbooks can influence production selection. Those factors are engineering inputs outside the benchmark result, not additional throughput or response-time evidence.
A practical Java-first rule looks like this:
If the service is part of a Java platform,
and either peak-throughput envelope or near-limit p95/p99 behavior is the deciding benchmark criterion,
then start with Java Helidon SE on the measured Oracle JDK runtime shape closest to the service goal.
If JVM diagnostics, Java libraries, Helidon SE integration, existing deployment pipelines,
or incident runbooks dominate the operational decision,
treat those as separate production inputs and verify the measured tradeoffs
under your actual service path.
That is a defensible position in an architecture review. It does not pretend Java wins every row. It says exactly where the Article 9 evidence supports Java and where production operations may reasonably keep Java as the preferred runtime for this service boundary.
CPU and GC do not collapse into one runtime ranking
CPU per 1,000 RPS and Java GC pause evidence are useful, but they do not produce a single Go-versus-Java ranking.
Some measured Java near-limit cells used less CPU per 1,000 RPS than Go. Other cells used more. The answer depended on fixture and CPU shape. That means CPU is not a simple tie-breaker for either side. If CPU per unit throughput is your deciding metric, read the matching row from Article 9 rather than quoting one runtime label.
Because the CPU result is mixed across Article 9’s displayed fixture and CPU-shape cells, this article does not recommend a runtime from CPU alone. If CPU cost is the constraint, choose the row that matches your service shape and retest with your real dependencies.
GC evidence needs the same discipline. Article 9’s Java GC pause evidence helps compare the two measured Java runtime shapes. It does not compare symmetrically with Go runtime counters, and it does not explain all response-time behavior by itself. Response time also includes request handling, scheduling, serialization, CPU availability, memory behavior, and the load point.
A compact Java-only reading is enough here:
The oracle-jdk-26-jvm shape is the Java baseline for this benchmark. Its GC pause burden varied by fixture and CPU shape.
The oracle-jdk-26-aot shape had lower GC pause milliseconds per workload second in several near-limit Java cells, but not all. Its p95 and max pause values also varied by cell.
Use GC pause evidence as Java runtime-burden context. Keep it as one part of the latency story, not the whole story.
This is one of the useful things Article 9 added. Without GC evidence, Java tail behavior is easy to explain by assumption. With GC evidence, we can talk about measured Java runtime burden. But response time is still the result of the full request path, not one counter.
What the oracle-jdk-26-aot shape showed
The oracle-jdk-26-aot result is useful, but it is also the easiest result to overstate.
In this article, oracle-jdk-26-aot means the specific measured Article 9 Java runtime configuration with that label. It was not a GraalVM Native Image executable. Read it as a measured runtime shape for this Helidon SE service under this benchmark setup, not as a general Project Leyden benchmark result, a GraalVM Native Image result, or proof that every Java application will start faster, use less memory, or deliver better steady-state throughput.
What did Article 9 show? The AOT-labeled runtime changed the Java profile in some cells. It led three of nine peak-throughput cells. It often had lower near-limit p95 and p99 than the JVM shape, but not always. It sometimes had lower RSS than the JVM shape, but not consistently. Its GC pause burden was lower in several near-limit cells, but not all.
That is useful precisely because it is bounded. The AOT-labeled runtime deserves a place in a Java evaluation for a similar service boundary. It should not be treated as a universal improvement over the JVM shape.
A safe way to use the result is:
If you want Java Helidon SE,
and the service resembles the benchmark,
and runtime-shape differences inside Java are important,
then include both the oracle-jdk-26-jvm and oracle-jdk-26-aot shapes in your local test.
Measure startup, warmup, RSS, CPU, GC, and steady-state behavior under your own service path.
If startup or warmup is part of your reason for exploring an AOT-shaped path, measure startup and warmup directly in your environment. Article 9’s public interpretation focused on throughput, response time, RSS, CPU, and Java GC evidence. Keep startup and warmup as separate measurements unless your own test captures them.
What changed from the first article’s benchmark framing
Article 1 set the benchmark contract and the questions. Article 9 supplied the measured results, so the guidance can now move from planned evaluation criteria to evidence-backed runtime-selection criteria.
At the start of the series, the responsible language was about what we planned to test: equivalent work, Go net/http, Helidon SE, Oracle JDK runtime scope, load-generator validation, CPU and memory visibility, warmup, repeats, resource metrics, and analysis discipline.
Article 9 changed the conversation because it gave us measured results. We no longer have to talk only about expectations or fairness principles. We can tie runtime guidance to measured result categories:
Runtime-selection reading: Favored the measured Java runtime shapes
Resident memory
Runtime-selection reading: Favored Go
CPU per 1,000 RPS
Runtime-selection reading: Mixed by fixture and CPU shape
Java GC pause evidence
Runtime-selection reading: Helped describe Java runtime burden without proving full response-time causality
oracle-jdk-26-aot
Runtime-selection reading: Changed the Java profile in some cells but was not a universal improvement over the JVM shape
That matters to different readers for different reasons.
Developers can use the result to choose a first implementation candidate for a similar compact service. Platform engineers can separate throughput, memory, CPU, and high-load response-time criteria instead of arguing about one runtime label. Performance reviewers can check that the recommendation follows the metric. Engineering leaders can use the result in standards discussions without turning it into a blanket Go-versus-Java claim.
The next step is practical: pick the criterion your service actually cares about, choose the runtime shape that Article 9 supports for that criterion, and then measure your representative service path.
How far these findings travel
The findings travel best to services that look like the benchmark: compact Linux HTTP services where local request handling, runtime scheduling, serialization, CPU use, memory footprint, and response-time behavior are meaningful parts of the service boundary.
The result supports workload-specific comparisons among the measured Article 9 runtime shapes. It does not support a universal Go-versus-Java conclusion.
It supports runtime-selection guidance for a compact, intentionally simple, single-service-host Linux HTTP benchmark under Article 9’s documented load-generation setup. It does not support claims about production microservices with databases, caches, queues, remote APIs, service meshes, or complex network dependencies unless those paths are separately measured.
It supports comparison of Go net/http with the measured Java Helidon SE runtime shapes under the Article 9 setup. It does not support claims about all Go frameworks, all Java frameworks, all Helidon services, or all JVM distributions.
It supports interpretation of peak throughput, pooled fixed-rate response time, near-limit p95/p99, resident memory, CPU per 1,000 RPS, and Java GC pause evidence as reported in Article 9. It does not support claims about Kubernetes autoscaling, pod density, cloud cost, multi-node scaling, or platform scheduling behavior unless your own test includes those factors.
It supports treating oracle-jdk-26-aot as one measured Oracle JDK AOT-labeled runtime configuration in this benchmark. It does not support treating that configuration as proof of universal Java startup, footprint, steady-state throughput, or Project Leyden behavior.
These boundaries should make the result more useful, not less. A benchmark that carries its boundary is easier to cite responsibly.
A bounded way to summarize the result is:
For a compact Linux HTTP service shaped like Article 9, Java Helidon SE on the measured oracle-jdk-26-jvm and oracle-jdk-26-aot shapes had the stronger peak-throughput and near-limit p95/p99 evidence, while Go net/http had the stronger pooled fixed-rate response-time and resident-memory evidence.
That is different from saying:
Java is faster than Go.
Or:
Go is always better for microservices.
Or:
The AOT-labeled runtime proves Java startup and footprint are solved.
The bounded statement helps a team choose what to test first. The broad statements start a language argument and hide the actual evidence.
Applying the result to a real service path
Use Article 9 as a first filter, then build a representative test for the real service path.
Suppose you are building a retrieval API for an AI application. The service accepts a JSON request, validates tenant policy, prepares a vector-search query, calls a database, formats candidate chunks, and returns a response to another service.
Article 9 helps you reason about the local service-tier portion: HTTP request handling, JSON work, deterministic local work, runtime scheduling, resident memory, CPU, and response-time behavior under the benchmark setup.
It does not tell you the vector-search latency. It does not tell you the SQL plan quality. It does not tell you connection-pool behavior. It does not tell you embedding model latency. It does not tell you how tracing, TLS, retries, or structured logging changes the p99.
So use the benchmark as a first filter:
If resident memory density and Article 9’s pooled fixed-rate response-time view dominate the service-tier decision, prototype Go net/http early.
If peak-throughput envelope, near-limit p95/p99, JVM diagnostics, Java libraries, Helidon SE fit, or existing Java operations dominate, prototype Java Helidon SE on the measured Article 9 Oracle JDK runtime shapes early.
If Java is already likely and runtime-shape behavior matters, include both oracle-jdk-26-jvm and oracle-jdk-26-aot in the local comparison.
If database calls, model calls, TLS, logging, tracing, retries, or failure behavior dominate the path, build a representative test before standardizing.
The goal is not to make the benchmark bigger for the sake of looking realistic. The goal is to make your next measurement representative of the decision you need to make.
Conclusion: Choose the metric, then choose the runtime
Use Article 9 to narrow the runtime choice for services that resemble the benchmark. Use your own measurements to make the production decision.
Peak throughput for this compact service shape
Reasonable starting point: Java Helidon SE on the measured Article 9 Oracle JDK runtime shapes
Article 9’s pooled fixed-offered-rate response-time view
Reasonable starting point: Go net/http
Measured resident memory footprint
Reasonable starting point: Go net/http
Near-limit p95/p99 at the 95pct-go-peak basis
Reasonable starting point: The measured Java runtime shapes
CPU per 1,000 RPS
Reasonable starting point: The matching fixture and CPU-shape cell in Article 9
JVM diagnostics, Java ecosystem fit, Helidon SE integration, and existing operational standards
Reasonable starting point: Java Helidon SE may remain the more defensible starting point for this service boundary
The final answer is not “Go wins” or “Java wins.” The final answer is more useful:
Choose the measured runtime shape supported by the metric that matters for your service, and keep the benchmark boundary attached.
That is how to use a benchmark as engineering evidence instead of a language contest. Measure the boundary, interpret response time with resource evidence, and choose the runtime your workload and team can defend.
So, can a Java HTTP service shaped like this benchmark be competitive with the measured Go service? For this benchmark-bounded case, yes. In this compact HTTP service benchmark, the Java Helidon SE implementation running on the tested Article 9 Oracle JDK runtime shapes was competitive with the Go net/http implementation under the documented hardware, load-generation method, and reported Article 9 metrics.
That is a useful result for runtime selection. It is not a universal law about every Java service, every Go service, or every production workload.
]]>https://redstack.dev/2026/11/05/what-the-go-and-java-benchmark-really-says-about-choosing-a-runtime/feed/04917Go and Java Service-Tier Benchmark Results for Oracle AI Database-Backed Applications
https://redstack.dev/2026/11/03/go-and-java-service-tier-benchmark-results-for-oracle-ai-database-backed-applications/
https://redstack.dev/2026/11/03/go-and-java-service-tier-benchmark-results-for-oracle-ai-database-backed-applications/#respondTue, 03 Nov 2026 17:21:00 +0000https://redstack.dev/?p=4889Continue reading →]]>Key Takeaways
Under this benchmark contract, the Oracle JDK Java runtime shapes led the peak-throughput results. The oracle-jdk-26-jvm shape led six of nine fixture/CPU-shape peak cells, and the oracle-jdk-26-aot shape led the other three.
Response time depended on the comparison point. In the pooled fixed-offered-rate view, Go had the lowest p50, p95, p99, and mean response time. At the 95pct-go-peak near-limit basis, both Java runtime shapes had lower median p95 and p99 response-time values than Go in every displayed fixture/CPU-shape cell.
Memory was the clearest resource tradeoff. Go used much lower measured service RSS in every displayed near-limit row, both as raw resident memory and normalized as RSS per 1,000 RPS.
CPU efficiency did not collapse into one simple ranking. CPU per 1,000 RPS varied by fixture and CPU shape, while Java GC pause evidence helped describe the Java runs without proving full response-time causality.
A service tier in front of Oracle AI Database can sit directly in the hot path. It might validate requests before calling vector search, enrich context before a model call, serve retrieval results to an AI application, or expose a compact HTTP endpoint that has to stay fast under load.
At low volume, runtime choice may not dominate. At higher volume, request scheduling, JSON handling, memory footprint, CPU use, and tail response time become capacity questions.
This is the ninth article in a ten-part, single-machine Linux benchmark series comparing Go and Java service-tier implementations for Oracle AI Database-backed application patterns. The earlier articles established the benchmark contract: equivalent service behavior, Go net/http and Java Helidon SE implementation choices, load generation, run rules, result validation, and analysis discipline.
This article reads the benchmark evidence. It does not rerun the benchmark, change the benchmark contract, or turn the results into runtime-selection advice. That guidance belongs in the next article.
The scope is deliberately narrow. This article compares specific service implementations and runtime shapes under a single-machine Linux HTTP benchmark contract. It does not compare programming languages in the abstract. It also does not measure Oracle AI Database performance, vector search, RAG quality, model inference, TLS, request logging, Kubernetes, autoscaling, cloud deployment, or production fleet behavior.
The tables and charts below use only benchmark runs that passed the validation checks defined earlier in the series.
Runtime Variants Compared
The benchmark result files use compact runtime identifiers. The article uses shorter display labels in tables and charts, but the mapping is always the same:
Benchmark runtime identifier
Display label used here
What it means in this article
go-http
Go
The Go service implementation using Go net/http
oracle-jdk-26-jvm
Oracle JDK JVM shape
The Helidon SE Java service running on the benchmark JVM shape
oracle-jdk-26-aot
Oracle JDK AOT-shaped runtime
The Helidon SE Java service running as the benchmark’s oracle-jdk-26-aot runtime shape
The Go rows represent the benchmark’s net/http implementation and runtime configuration.
The Java implementation in this benchmark used Helidon SE as configured by the benchmark contract. These results apply to that service implementation and runtime configuration, not to all Helidon services or all Java web frameworks.
The Java rows use the specific Oracle JDK build and runtime artifacts named by the benchmark results. They should not be generalized to every OpenJDK distribution or to untested JVM flags.
The oracle-jdk-26-aot label is deliberately narrow. In this article, oracle-jdk-26-aot means the benchmark-defined Oracle JDK AOT-shaped variant only. It is not a general Project Leyden benchmark result, not a GraalVM Native Image benchmark result, and not evidence for all Java AOT approaches. Do not infer an AOT implementation mechanism, startup behavior, or production deployment model from the label unless it is stated in the benchmark contract.
The CPU shape column uses the benchmark labels 1, 4, and all. Read those as part of the run contract for each result cell, not as a general statement about every host shape or deployment environment. The all label means the benchmark’s “all available CPUs for this run contract” shape; it should not be converted into a portable core count without the benchmark machine details.
How to read the benchmark comparisons
There are three comparison styles in this article.
A peak result reports the strongest throughput result for a benchmark cell. A cell combines the fixture, payload size, CPU shape, runtime shape, process topology, concurrency, and measurement basis. Treat each row as a cell-scoped result, not as a universal statement about Go or Java.
A comparable-rate result compares response time at a common offered-rate basis. This matters because response time from one runtime near saturation should not be casually compared with response time from another runtime at a lighter load point.
A near-limit result in this article means the 95pct-go-peak rate tier. For each fixture and CPU shape, the offered request rate is derived from Go’s measured peak for that same fixture and CPU shape. That lets us ask a practical question: if the service tier is operating near Go’s measured ceiling for this workload cell, how do the other runtime shapes behave at the same offered rate?
The article reports externally observed request durations at named offered-rate tiers. It does not make a coordinated-omission-correction claim; response-time results should be read as benchmark-output measurements under the documented load-generation and analysis contract.
The ratio tables use Go as the denominator for the same fixture and CPU shape:
ratio versus Go = measured value for comparison runtime / measured Go value
Metric direction matters:
Throughput: higher is better.
Response time: lower is better.
RSS: lower is better.
CPU per 1k RPS: lower is better.
RSS per 1k RPS: lower is better.
GC pause metrics: lower is generally better, but they are Java-only context.
Two normalized resource metrics appear often:
CPU per 1k RPS = service CPU percent / (achieved RPS / 1000)
RSS per 1k RPS = service RSS MiB / (achieved RPS / 1000)
The CPU values use the benchmark’s recorded service-process CPU percentage basis. Values can exceed 100 when the service consumes more than one core-equivalent of CPU during the measurement window.
Normalized metrics are useful for capacity reasoning, but they do not remove the benchmark context. Read them alongside the absolute values.
Pooled fixed-offered-rate response time
Before peak and near-limit results, the pooled fixed-offered-rate view gives useful context.
This is not a peak-throughput table. It is not the same aggregation basis as the later near-limit median tables. It answers a narrower question: across the fixed-offered-rate records in this view, what externally observed response-time distribution did each runtime shape produce?
Because this table is pooled across fixed-offered-rate records in the view, it is useful for broad context. It is not a substitute for the cell-scoped peak and near-limit tables later in the article.
Runtime shape
p50 response time (ms)
p95 response time (ms)
p99 response time (ms)
Mean response time (ms)
Max response time (ms)
Measured requests
go-http
0.266
0.478
0.704
0.298
53.974
2,268,000
oracle-jdk-26-aot
0.282
0.585
0.888
0.327
22.276
2,268,000
oracle-jdk-26-jvm
0.280
0.590
0.912
0.328
30.302
2,268,000
Note the unit change between sections: this pooled fixed-rate table reports response time in milliseconds, while the near-limit table later reports response time in microseconds.
In this pooled fixed-offered-rate view, Go had the lowest p50, p95, p99, and mean response time. The two Java runtime shapes were close to each other. The AOT-shaped runtime was slightly lower at p95, p99, mean, and max; the JVM shape was slightly lower at p50.
That does not contradict the near-limit result later in the article. The pooled table summarizes records from a fixed-offered-rate matrix. The near-limit table summarizes median benchmark-output metrics at the 95pct-go-peak offered-rate tier.
The practical reading: fixed-rate response time is valid only when the offered-rate basis is named. It is useful context, but it should not be used as a substitute for peak or near-limit results.
Peak throughput by benchmark cell
Peak throughput is the first result group most readers ask for.
In the peak-throughput summary table, the Oracle JDK JVM shape led six of nine fixture/CPU-shape cells, and the Oracle JDK AOT-shaped runtime led the other three. Go did not lead a peak-throughput cell in this table.
That is a meaningful benchmark result, but it is still cell-scoped. It describes the service implementations, fixture sizes, CPU shapes, concurrency choices, and single-machine measurement contract. It is not a language-wide ranking.
Fixture
CPU shape
Peak runtime shape
Achieved RPS
Concurrency
Service RSS MiB
Service CPU %
work-128b
1
Oracle JDK JVM shape
29701.20
64
137.71
105.11
work-128b
4
Oracle JDK JVM shape
63826.00
256
588.10
244.71
work-128b
all
Oracle JDK JVM shape
60011.60
256
608.05
298.49
work-2kb
1
Oracle JDK JVM shape
24696.93
64
130.95
110.13
work-2kb
4
Oracle JDK JVM shape
59083.20
256
619.54
256.34
work-2kb
all
Oracle JDK AOT-shaped runtime
62772.07
256
617.85
322.43
work-32kb
1
Oracle JDK AOT-shaped runtime
11289.87
16
123.32
104.31
work-32kb
4
Oracle JDK JVM shape
41654.40
256
416.20
319.63
work-32kb
all
Oracle JDK AOT-shaped runtime
52697.73
256
468.93
458.27
This table shows only the winning runtime shape for each peak cell. The ratio chart that follows compares the peak values against the matching Go baseline for the same fixture and CPU shape.
The strongest peak-throughput value in the table was 63826.00 RPS for the Oracle JDK JVM shape on work-128b, CPU shape 4.
The strongest AOT-shaped peak-winning cell was 62772.07 RPS on work-2kb, CPU shape all.
Figure 1: Peak throughput by runtime, fixture, and CPU shape. Higher is better.
Figure 2: Throughput ratio versus the Go baseline. Higher is better for throughput; each ratio is scoped to matching benchmark cell dimensions.
Figure 3: Service CPU at each runtime’s peak-throughput cell. Lower is better only when compared at similar throughput; read this beside Figure 1.
Figure 4: Resident memory at each runtime’s peak-throughput cell. Lower is better.
Figure 5: Peak throughput versus RSS footprint. Higher and farther left is better.
The charts make the throughput pattern easier to scan. The Oracle JDK Java runtime shapes were strong in the peak-throughput envelope. But peak RPS alone is not the full operating story. A service that delivers more peak throughput can still use more memory, have a different CPU profile, or behave differently at common request rates.
The practical reading: under this benchmark contract, the peak-throughput winners were the two Oracle JDK Java runtime shapes. Carry that forward as workload-specific service-tier evidence, not as a universal claim about all Go or Java services.
Throughput per configured CPU core
Peak RPS answers, “How much traffic did the cell deliver?”
Throughput per configured CPU core asks, “How much traffic did the cell deliver per CPU shape used by the benchmark cell?”
That distinction matters in platform planning. If an application service tier has a fixed CPU budget, peak RPS alone can hide whether a runtime shape used that budget efficiently.
Figure 6: Peak throughput per configured CPU core. Higher is better; this normalized view should be read alongside absolute throughput values.
The per-core chart keeps the main peak story visible while adding a capacity lens. Some cells that look close in raw RPS separate more clearly after CPU normalization; other cells remain close.
The important discipline is not to turn throughput per core into a universal efficiency law. It is a normalized view for these benchmark cells on this benchmark machine.
The practical reading: throughput per core supports capacity analysis inside the benchmark contract. It should be read beside absolute RPS, response time, CPU per 1k RPS, and memory.
Response time at comparable request rates
Response-time comparisons are easy to misuse. If one runtime is near saturation and another is running far below its own peak, their p95 or p99 values are not telling the same story unless the rate basis is named.
The benchmark evidence includes a moderate 80%-of-Go-peak view and a near-limit 95%-of-Go-peak view. Both are Go-derived common offered-rate bases. They compare runtime shapes at request rates tied to Go’s measured peak for the same fixture and CPU shape.
Figure 7: P95 response time at the fixed 5,000 RPS comparison point. Lower is better.
The fixed 5k RPS chart is the lowest common offered-rate view. It is useful because it compares all three runtime shapes at the same modest request rate before the higher-rate Go-derived tiers.
Figure 8: P95 response time at the 80%-of-Go-peak comparison point. Lower is better.
The 80%-of-Go-peak view is the more moderate common-rate chart. It is useful when asking what happens below the near-limit tier.
The near-limit view is more demanding. It asks what happens close to Go’s measured operating ceiling for the same fixture and CPU shape.
The normalized CPU and RSS columns use achieved RPS from the benchmark result output. The table displays the offered RPS tier for readability; achieved RPS is the denominator used in the normalized metrics.
The table below reports the median p50, p95, and p99 response-time values at 95pct-go-peak, together with RSS and normalized resource metrics.
Fixture
CPU shape
Offered RPS
Runtime shape
p50 (µs)
p95 (µs)
p99 (µs)
RSS MiB
CPU per 1k RPS
RSS MiB per 1k RPS
work-128b
1
13300
Go
14458.50
31988.00
41066.50
25.33
6.80
1.90
work-128b
1
13300
Oracle JDK AOT-shaped runtime
253.00
2670.00
8690.00
167.45
7.23
12.59
work-128b
1
13300
Oracle JDK JVM shape
425.00
12164.00
21468.50
190.93
8.07
14.36
work-128b
4
39300
Go
3311.50
14719.50
22601.00
28.18
6.83
0.72
work-128b
4
39300
Oracle JDK AOT-shaped runtime
515.00
5556.00
10490.00
703.98
5.84
17.91
work-128b
4
39300
Oracle JDK JVM shape
865.50
6900.00
12394.00
623.88
5.94
15.87
work-128b
all
43000
Go
2131.00
17640.00
30183.00
32.31
8.37
0.75
work-128b
all
43000
Oracle JDK AOT-shaped runtime
487.50
4228.00
8192.00
528.12
7.08
12.28
work-128b
all
43000
Oracle JDK JVM shape
615.00
5381.00
9500.50
519.51
7.31
12.08
work-2kb
1
11900
Go
3561.00
19691.00
31845.50
25.60
6.89
2.15
work-2kb
1
11900
Oracle JDK AOT-shaped runtime
234.50
1649.00
6662.00
177.25
8.64
14.89
work-2kb
1
11900
Oracle JDK JVM shape
225.00
1349.00
7511.50
177.60
8.01
14.92
work-2kb
4
37400
Go
1931.50
12966.50
20836.00
28.43
7.13
0.76
work-2kb
4
37400
Oracle JDK AOT-shaped runtime
362.50
3248.50
7243.50
725.62
6.46
19.40
work-2kb
4
37400
Oracle JDK JVM shape
462.50
4999.50
10068.00
484.54
6.11
12.96
work-2kb
all
38700
Go
738.50
8753.00
16220.50
31.77
8.86
0.82
work-2kb
all
38700
Oracle JDK AOT-shaped runtime
540.50
5377.50
10787.50
558.51
7.82
14.43
work-2kb
all
38700
Oracle JDK JVM shape
459.00
4135.50
7914.00
427.24
7.83
11.04
work-32kb
1
7000
Go
701.50
40501.50
54907.00
25.22
11.54
3.60
work-32kb
1
7000
Oracle JDK AOT-shaped runtime
286.00
5307.50
18049.00
167.81
13.80
23.97
work-32kb
1
7000
Oracle JDK JVM shape
295.00
13849.50
35251.00
180.66
16.17
25.81
work-32kb
4
25300
Go
3223.50
18709.00
30260.50
28.30
12.06
1.12
work-32kb
4
25300
Oracle JDK AOT-shaped runtime
383.00
4620.00
10277.50
349.23
10.63
13.80
work-32kb
4
25300
Oracle JDK JVM shape
514.00
7137.50
13662.50
386.17
10.78
15.26
work-32kb
all
33200
Go
6481.00
36525.50
54315.00
32.79
9.17
0.99
work-32kb
all
33200
Oracle JDK AOT-shaped runtime
2734.00
13070.00
20251.00
489.96
10.35
14.76
work-32kb
all
33200
Oracle JDK JVM shape
3903.50
15295.50
22368.00
586.55
9.82
17.67
At the 95pct-go-peak offered-rate targets, both Java runtime shapes showed lower median p95 and p99 response-time values than Go in every displayed fixture/CPU-shape cell.
On work-128b, CPU shape 1, Go p95 was 31988.00 µs, the AOT-shaped runtime p95 was 2670.00 µs, and the JVM shape p95 was 12164.00 µs.
On work-2kb, CPU shape all, the p95 gap was smaller: Go was 8753.00 µs, the AOT-shaped runtime was 5377.50 µs, and the JVM shape was 4135.50 µs.
Figure 9: Near-limit p95 response time by benchmark cell. Lower is better.
Figure 10: Near-limit p99 response time by benchmark cell. Lower is better.
Figure 11: P95 response time across comparable offered-rate tiers. Lower is better.
On work-32kb, CPU shape all, Go p99 was 54315.00 µs, the AOT-shaped runtime was 20251.00 µs, and the JVM shape was 22368.00 µs. That difference sits beside a large RSS difference in the opposite direction.
The practical reading: response time is load-point-sensitive. In the pooled fixed-offered-rate view, Go had the lowest aggregate p50, p95, p99, and mean response time. At the 95pct-go-peak near-limit basis, both Java runtime shapes had lower median p95 and p99 response-time values than Go in every displayed fixture/CPU-shape cell.
CPU per 1k RPS is workload-specific
CPU per 1k RPS asks how much measured service CPU was associated with each thousand requests per second. Lower is better within this benchmark scope.
This metric avoids a common trap: a runtime can lead on peak throughput but still consume more CPU per unit of delivered throughput in some cells. Or it can use less CPU per unit throughput in one payload shape and more in another.
Figure 12: Near-limit CPU used per one thousand requests per second. Lower is better.
The CPU story is not a one-direction runtime ranking.
In several near-limit cells, the Java runtime shapes used less CPU per 1k RPS than Go. On work-128b, CPU shape 4, Go used 6.83, the AOT-shaped runtime used 5.84, and the JVM shape used 5.94. On work-2kb, CPU shape 4, Go used 7.13, the AOT-shaped runtime used 6.46, and the JVM shape used 6.11.
In other cells, Go used less CPU per 1k RPS. On work-32kb, CPU shape 1, Go used 11.54, the AOT-shaped runtime used 13.80, and the JVM shape used 16.17. On work-2kb, CPU shape 1, Go used 6.89, the AOT-shaped runtime used 8.64, and the JVM shape used 8.01.
For platform teams, the useful point is that CPU cost depends on fixture and CPU shape. Read the cell; do not read only the runtime label.
The practical reading: CPU per 1k RPS is mixed. Some Java cells had lower normalized service CPU than Go; others had higher normalized service CPU. This is workload-specific capacity evidence, not a universal CPU-efficiency score.
Figure 13: Near-limit CPU per 1k RPS ratio versus the Go baseline. Lower is better.
RSS and RSS per 1k RPS show the clearest resource tradeoff
Memory is the cleanest contrast in the near-limit rows.
Go’s measured service RSS stayed in a narrow band from 25.22 MiB to 32.79 MiB across the displayed near-limit cells. The AOT-shaped Java runtime ranged from 167.45 MiB to 725.62 MiB. The JVM-shaped Java runtime ranged from 177.60 MiB to 623.88 MiB.
That is not a footnote. It is one of the main results.
Figure 14: Near-limit resident set size by benchmark cell. Lower is better for footprint.
RSS means resident memory under the benchmark conditions. It is not a Kubernetes memory request, a production heap-sizing rule, or a container limit recommendation. It depends on service implementation, runtime configuration, operating-system accounting, process topology, and collection method.
Even with that boundary, the pattern is large enough to matter. In this evidence set, Go had much lower measured service RSS than both Java runtime shapes in every displayed near-limit fixture/CPU-shape cell.
RSS per 1k RPS normalizes that footprint by delivered throughput.
Figure 15: Near-limit resident set size normalized per one thousand requests per second. Lower is better.
Figure 16: RSS per 1k RPS across comparable offered-rate tiers. Lower is better.
Figure 17: Near-limit memory cost versus p95 response time. Lower left is better.
The normalized view preserves the same memory story.
On work-128b, CPU shape 4, Go used 0.72 MiB per 1k RPS, the AOT-shaped runtime used 17.91, and the JVM shape used 15.87.
On work-32kb, CPU shape all, Go used 0.99, the AOT-shaped runtime used 14.76, and the JVM shape used 17.67.
A runtime shape can be attractive for peak throughput and high-load response time while still costing more resident memory. That is exactly the kind of tradeoff this benchmark was designed to expose.
The practical reading: memory strongly favored Go in the near-limit evidence. The pattern held for both absolute RSS and RSS per 1k RPS across every displayed near-limit row.
Near-limit ratios versus the Go baseline
The near-limit table gives raw values. Ratios compress the comparison against the Go denominator for the same fixture and CPU shape.
Ratios are useful only when direction is explicit:
A p95 ratio below 1.0 means lower p95 response time than Go for that cell.
An RSS ratio above 1.0 means higher resident memory than Go for that cell.
A CPU-per-1k ratio below 1.0 means lower CPU per unit throughput than Go for that cell.
In the near-limit ratio rows, AOT-shaped p95 ratios versus Go ranged from 0.08 to 0.61, while JVM-shaped p95 ratios versus Go ranged from 0.07 to 0.47.
For the displayed near-limit cells, Java RSS ratios versus the matching Go row ranged from 6.61x to 25.53x. That ratio describes resident memory only; it does not include heap limits, container requests, or production memory policy.
CPU-per-1k ratios varied by cell, with some Java rows below 1.0 and others above 1.0.
Figure 18: Near-limit p95 response-time ratio versus the Go baseline. Lower is better for response time.
Figure 19: Near-limit RSS ratio versus the Go baseline. Lower is better for memory footprint.
This chart is useful precisely because it is compact. It is also easy to overread. A ratio shows relative magnitude inside a cell. It does not explain the cause, and it does not predict a different service, host, payload mix, database access pattern, or runtime configuration.
The practical reading: the near-limit ratio view makes two patterns obvious. Java p95 and p99 ratios were below Go at the Go-derived near-limit basis, while Java RSS ratios were much higher than Go. CPU ratios varied by cell.
Java GC pause evidence for the Java runs
The GC pause evidence is Java-only evidence. It comes from Java GC pause measurements collected for Oracle JDK workload windows. It is useful runtime-burden context.
It is not a symmetric comparison with Go runtime counters, and it should not be used alone to explain every response-time pattern. In the GC table, “measured events” refers to the event denominator used by the Java GC analysis output, not to GC events unless explicitly stated by the benchmark artifacts.
Fixture
CPU shape
Runtime shape
Offered RPS
GC pause ms per workload second
GC pause ms per 1k measured events
GC pause p95 ms
GC pause max ms
work-128b
1
AOT-shaped runtime
13300
13.96
1.40
2.59
12.35
work-128b
1
JVM shape
13300
13.14
1.32
2.61
7.97
work-128b
4
AOT-shaped runtime
39300
8.85
0.30
8.14
9.05
work-128b
4
JVM shape
39300
9.08
0.31
5.69
7.20
work-128b
all
AOT-shaped runtime
43000
11.43
0.35
8.63
10.33
work-128b
all
JVM shape
43000
12.45
0.39
10.82
11.95
work-2kb
1
AOT-shaped runtime
11900
15.53
1.74
2.89
8.06
work-2kb
1
JVM shape
11900
15.56
1.74
3.12
5.15
work-2kb
4
AOT-shaped runtime
37400
7.89
0.28
7.36
7.40
work-2kb
4
JVM shape
37400
8.50
0.30
6.80
9.42
work-2kb
all
AOT-shaped runtime
38700
10.84
0.37
11.44
12.47
work-2kb
all
JVM shape
38700
10.11
0.35
6.96
10.91
work-32kb
1
AOT-shaped runtime
7000
9.31
1.77
2.96
12.50
work-32kb
1
JVM shape
7000
8.76
1.67
2.73
6.73
work-32kb
4
AOT-shaped runtime
25300
6.15
0.32
4.40
5.94
work-32kb
4
JVM shape
25300
8.15
0.43
6.48
20.75
work-32kb
all
AOT-shaped runtime
33200
9.92
0.40
7.71
13.91
work-32kb
all
JVM shape
33200
10.39
0.42
8.09
9.03
The Java GC story is mixed.
The AOT-shaped runtime was numerically lower than the JVM shape for GC pause milliseconds per workload second in several near-limit cells: work-128b CPU shape 4, work-128b CPU shape all, work-2kb CPU shape 1, work-2kb CPU shape 4, work-32kb CPU shape 4, and work-32kb CPU shape all.
The JVM shape was lower in other cells: work-128b CPU shape 1, work-2kb CPU shape all, and work-32kb CPU shape 1.
The p95 and max pause columns vary too. On work-32kb, CPU shape 4, the JVM shape had a max GC pause of 20.75 ms, while the AOT-shaped runtime had 5.94 ms. On work-128b, CPU shape 1, the AOT-shaped runtime had a higher max pause, 12.35 ms, compared with the JVM shape at 7.97 ms.
Figure 20: Java GC pause milliseconds per workload second at the near-limit comparison point. Lower is generally better; this chart provides runtime-burden context for the Java runs.
Figure 21: Java GC pause burden across comparable offered-rate tiers. Lower is generally better.
The GC chart helps avoid hand-waving. Without GC logs, Java tail behavior is often explained by assumption. With GC logs, we can at least say what pause burden was visible in the Java evidence.
But response time also includes request handling, scheduling, serialization, CPU availability, memory behavior, and load point.
The practical reading: Java GC pause evidence was visible and varied by runtime shape, fixture, and CPU shape. It helps interpret the Java runs, but it does not replace the response-time tables or prove full latency causality.
The oracle-jdk-26-aot runtime shape changed the profile, but not uniformly
The oracle-jdk-26-aot result should stay tied to the measured runtime shape.
This article does not claim startup behavior, does not benchmark all Java AOT approaches, and does not describe this as a GraalVM Native Image result.
In the benchmark evidence, the AOT-shaped runtime changed the measured Java profile across some throughput, response-time, RSS, CPU, and GC-pause observations. It did not produce a blanket improvement over the JVM shape across every fixture, CPU shape, and metric.
At peak throughput, the AOT-shaped runtime led three of nine fixture/CPU-shape cells:
Fixture
CPU shape
AOT-shaped peak RPS
Peak-throughput result
work-2kb
all
62772.07
Peak leader
work-32kb
1
11289.87
Peak leader
work-32kb
all
52697.73
Peak leader
The JVM shape led the other six peak cells. That means the AOT-shaped runtime was not a universal peak-throughput improvement over the JVM shape in this benchmark.
Near the Go-derived limit, the AOT-shaped runtime often had lower p95 and p99 response time than the JVM shape, but not always.
On work-128b, CPU shape 1, AOT-shaped p95 was 2670.00 µs while JVM-shaped p95 was 12164.00 µs. On work-32kb, CPU shape 4, AOT-shaped p95 was 4620.00 µs while JVM-shaped p95 was 7137.50 µs.
But on work-2kb, CPU shape all, the JVM shape had lower p95 and p99: JVM-shaped p95 was 4135.50 µs compared with AOT-shaped p95 at 5377.50 µs, and JVM-shaped p99 was 7914.00 µs compared with AOT-shaped p99 at 10787.50 µs.
RSS also did not produce a simple “AOT is smaller” result. On work-32kb, CPU shape all, AOT-shaped RSS was 489.96 MiB and JVM-shaped RSS was 586.55 MiB. On work-2kb, CPU shape 4, AOT-shaped RSS was 725.62 MiB and JVM-shaped RSS was 484.54 MiB.
The defensible statement is narrow and still useful: the AOT-shaped runtime changed the Java benchmark profile in some cells. It was not a universal improvement across all measured dimensions.
The practical reading: treat oracle-jdk-26-aot as a measured runtime-shape result. In this evidence, it helped some cells and metrics, but did not uniformly improve peak throughput, response time, memory footprint, CPU normalization, or GC pause burden versus the JVM shape.
Boundaries for using these Go and Java benchmark results
A benchmark result is useful only when its boundaries travel with it.
Boundary
What this article supports
What it does not support
Runtime scope
go-http, oracle-jdk-26-jvm, and oracle-jdk-26-aot as benchmark runtime variants
All Go services, all Java services, all Helidon services, or all JDK builds
Java distribution scope
The specific Oracle JDK build and runtime artifacts named by the benchmark results
Temurin, Eclipse Adoptium, other OpenJDK distributions, or untested JVM flags
AOT scope
The benchmark’s Oracle JDK AOT-shaped runtime cell
GraalVM Native Image, all Project Leyden behavior, or all Java AOT approaches
Workload scope
Single-machine Linux HTTP service workload with fixture and CPU shapes
Kubernetes, autoscaling, service mesh, multi-node scaling, production fleet behavior
Database scope
Service-tier context relevant to Oracle AI Database-backed AI applications
Oracle AI Database throughput, vector search, SQL performance, RAG quality, model inference, or storage behavior
Response-time scope
Externally observed request duration at named rate bases
Production SLO guarantees, coordinated-omission-correction claims, or latency rankings without matching load points
RSS scope
Measured resident memory under benchmark conditions
Production heap sizing, Kubernetes memory requests, or container limit recommendations
CPU scope
Service-process CPU normalized by delivered throughput
Universal runtime CPU efficiency
GC scope
Java GC pause evidence for Java cells
Complete response-time causality or a symmetric comparison with Go runtime counters
The benchmark is intentionally narrow so the comparisons can be meaningful. If you change the service logic, payload mix, database dependency, network path, TLS behavior, logging, container limits, JDK build, Go version, Helidon configuration, or host shape, measure again.
What the data supports
The data supports a tradeoff story, not a language-war slogan.
Peak throughput favored the Oracle JDK Java runtime shapes in the peak-throughput summary. The JVM shape led six of nine peak cells, and the AOT-shaped runtime led three. The strongest peak-throughput value was 63826.00 RPS for the JVM shape on work-128b, CPU shape 4.
Throughput per core reinforces that raw peak RPS is not the whole capacity story. It shows delivered work per configured core, which is often closer to the resource question platform teams ask.
Response time depends on rate basis. In the pooled fixed-offered-rate table, Go had the lowest p50, p95, p99, and mean response time. At the 95pct-go-peak near-limit basis, both Java runtime shapes had lower median p95 and p99 response-time values than Go in every displayed fixture/CPU-shape cell.
Memory strongly favored Go. In every displayed near-limit row, Go had much lower measured service RSS than both Java runtime shapes. RSS per 1k RPS preserved that memory-cost pattern.
CPU per 1k RPS was mixed. Some Java cells used less CPU per unit of delivered throughput than Go; others used more. The answer depends on fixture and CPU shape.
Ratios versus Go are useful scoped summaries. They make the near-limit p95 and RSS contrast obvious, but they must be read with the raw tables because metric direction changes.
Java GC pause evidence helps interpret the Oracle JDK runs, but it does not replace the response-time charts. GC pause burden varied by Java runtime shape, fixture, and CPU shape.
The AOT-shaped runtime changed the measured Java profile in some cells. It was not a universal improvement over the JVM shape, and it should not be read as a broad product or technology promise beyond the measured workload.
References and methodology notes
The numeric tables and charts in this article come from the benchmark results for this series. The tables preserve the result dimensions used by the analysis: fixture, CPU shape, runtime shape, offered-rate basis, and measured service metrics. The external references below provide product, API, and methodology context; they do not expand the measured benchmark scope.
Next: turning benchmark results into runtime choices
This article gives us enough evidence to say something concrete.
Under this benchmark’s single-machine Linux HTTP service workload, the Oracle JDK JVM and AOT-shaped runtime delivered the highest peak-throughput results in the recorded peak cells. Near the Go-derived high-load basis, the Java service shapes had lower median p95 and p99 externally observed response-time values in the near-limit output. Go used far less resident memory, both raw and normalized per 1,000 RPS. CPU efficiency depended on fixture and CPU shape. Java GC pause measurements showed real differences between JVM-shaped and AOT-shaped Java cells, but not a universal AOT advantage.
That is useful because it is specific.
The next article can translate these results into runtime-selection guidance: when peak throughput matters more than RSS, when memory density matters more than high-load headroom, when fixed-rate response time is the better comparison, and what to measure in an Oracle AI Database-backed AI service before choosing a runtime shape.
]]>https://redstack.dev/2026/11/03/go-and-java-service-tier-benchmark-results-for-oracle-ai-database-backed-applications/feed/04889How We Analyze Benchmark Data Before Claiming Anything
https://redstack.dev/2026/10/30/how-we-analyze-benchmark-data-before-claiming-anything/
https://redstack.dev/2026/10/30/how-we-analyze-benchmark-data-before-claiming-anything/#respondFri, 30 Oct 2026 16:16:00 +0000https://redstack.dev/?p=4881Continue reading →]]>Key Takeaways
A benchmark does not become trustworthy when the load test ends. It becomes more trustworthy when raw artifacts are normalized, invalid runs stay visible, repeated runs are aggregated consistently, and uncertainty stays attached to the published comparison.
This article defines the analysis contract for this benchmark series. Later articles use the same units, reporting rules, and chart constraints instead of inventing logic after seeing the numbers.
We do not treat throughput, tail latency, CPU, memory, runtime diagnostics, startup, and warmup as one scoreboard. Each metric family answers a different engineering question, so we report them separately.
The results article may compare variants within defined scenario and variant cells, but it may not declare an overall language winner. Exclusions, instability, and uncertainty remain visible wherever we make a comparison.
If you have ever read a benchmark post and thought, the chart is clean, but I still do not trust it, this is probably the missing layer.
Most benchmark arguments sound like methodology arguments, but a lot of the real trust problem shows up one step later, in analysis. The load test finishes. A directory fills up with raw outputs, logs, host metrics, and maybe runtime telemetry. Then someone has to decide what a “run” means, what gets excluded, how repeats get summarized, which latency numbers matter, and what kind of chart makes the comparison easiest to understand.
That is where a benchmark can drift from careful measurement into selective storytelling.
This article fixes the analysis contract before we publish results. Earlier entries in the series defined the run protocol, invalid-run logic, execution artifacts, and reproduction path. This article answers a narrower question: how do repeated benchmark runs become a published comparison that a skeptical engineer can inspect without guessing what got smoothed away?
The answer is disciplined rather than complicated. We commit now to the unit of analysis, the canonical dataset, the aggregation rules, the reporting rules, and the allowed plot types. We do that before the results article and before the interpretation article.
That matters because benchmark trust is not won by having more telemetry. It is won by making the path from raw artifacts to public claims easy to inspect.
We turn raw benchmark artifacts into reported comparisons through a fixed path: normalize each run, validate acceptance rules, aggregate by cell, surface exclusions and uncertainty, and only then choose allowed plots.
It is easy to treat methodology as the part that happens before measurement: define the service, define the workload, validate the load generator, run the matrix, keep the host stable. All of that matters, and we have already spent several articles making it explicit.
But once the measurement phase is over, the benchmark still is not done. At that point, you have evidence, not a result. The result only appears after you answer analysis questions that are easy to wave away and surprisingly easy to bias.
What exactly is the unit we compare? One run, one average, one percentile, one scenario, one runtime variant, or one bundle of unlike metrics?
What happens when one repeat fails startup, another has incomplete telemetry, and six more look fine?
Do we show the best repeat, the mean of accepted repeats, the median, a tail-focused summary, or some mashup of all three?
Do we keep startup and steady state separate, or quietly blend them into one performance story?
Do we show throughput with uncertainty signals and latency as a selected p99, or do we carry uncertainty through both?
Those are not cosmetic questions. They determine how much trust the reader should place in the claim.
That is why we are fixing the analysis rules now instead of letting the results article discover them on the fly. Later in the series, if a chart appears, it should be possible to ask three immediate questions and get concrete answers:
What exact cell does this chart summarize?
How many repeats were attempted and accepted?
What uncertainty or instability should stop me from overreading the difference?
If a chart cannot answer those questions, it does not belong in this series.
Benchmark terms we will use consistently
Before we talk about schema or aggregation, we need stable terms. These are series terms, not universal benchmark law, but we will use them consistently from here on.
A scenario is one workload definition. It captures payload size, concurrency target, workload mode, and the other settings that define what kind of test this is.
A variant is one runtime shape under test. Examples in this series include a Go service built on the standard-library net/http package and a Java service built with Helidon. These are benchmarked implementation shapes, not exhaustive representatives of either ecosystem.
A run is one executed measurement attempt for one scenario and one variant.
A repeat is one numbered run within a set of repeated attempts for the same scenario and variant combination. In practice, a repeat is usually just a run viewed in the context of its sibling attempts.
A cell is the combination of one scenario and one variant. This is the main unit of aggregation. We do not compare a loose pile of runs. We compare cells built from repeated runs under one fixed scenario and one fixed variant.
An accepted run is a run that passed the predeclared validation rules and is eligible for aggregation.
An invalid run is a run that failed those rules. Invalid does not mean invisible. It means excluded from the aggregated summaries and still reported with a reason class.
An unstable cell is a cell that meets the minimum bar for reporting but still triggers one or more warning conditions, such as higher-than-allowed repeat spread, missing metric slices, or incomplete evidence for one metric family.
Warmup is the interval where the service and runtime are getting into shape but we are not yet treating the behavior as steady measurement. For Java that can include JIT and class-loading effects; for Go it can still include allocator, scheduler, and cache stabilization. Either way, warmup is not the same thing as the main measurement window.
Steady state is the defined analysis window where service behavior is treated as the main comparable runtime state for throughput, latency, CPU, memory, and related metrics.
That vocabulary is intentionally boring. If those terms slide around between articles, the results slide around with them.
What the canonical benchmark dataset contains
A result chart should never be a pile of hand-entered summary numbers with the interesting mess stripped away. Our analysis starts from a canonical dataset that links the raw evidence to the derived metrics we actually publish.
The top-level shape is runtime-neutral. Go and Java both need to fit the same record model. Java-specific telemetry such as GC logs or Java Flight Recorder recordings can appear when captured, but they are additive fields, not proof that the schema belongs only to the JVM side.
At minimum, one normalized run record needs to connect scenario metadata, variant metadata, environment details, raw artifact references, analysis windows, derived metrics, and validation state.
Here is an intentionally schematic JSON example that shows the contract. Treat the field names, metric names, file paths, and IDs as illustrative only, not as the finalized benchmark schema.
The important thing here is not the exact spelling of the fields. It is the separation of concerns.
The record points to raw files instead of pretending the summaries appeared by magic. It separates startup, warmup, and steady-state windows so we do not flatten them together later, and those windows come from the predefined run protocol rather than being tuned after the numbers are in. It keeps derived metrics distinct from artifact references. And it carries validation state inside the same normalized object instead of hiding exclusions in a spreadsheet note.
That structure is especially useful on the Java side. The Java implementation in this series is one specific framework and runtime shape, not “Java” in the abstract. On HotSpot-based runs, the artifact set may also include service logs, GC logs, and Java Flight Recorder data where configured. Those artifacts are useful, but only if they are tied to a run ID and normalized into the same record model as the Go-side evidence rather than used as a separate storytelling layer.
The example record uses Linux as the host OS label, but the actual results package should identify the tested host environment with more precision. These are single-machine results, and kernel, distribution, CPU settings, and other host details can materially affect behavior.
Our analysis contract requires a manifest-style mapping from archived files to normalized inputs so the path from source artifact to reported metric stays inspectable.
A compact directory sketch can be as simple as this:
artifacts/
<scenario>/
<variant>/
<repeat>/
manifest.json
loadgen-output.json
service.log
runtime-log-or-trace.dat
And a matching manifest might look like this at a conceptual level. The keys and filenames below are illustrative placeholders, not verified repository literals:
{
"run_id":"<timestamp>-<variant>-r03",
"scenario_id":"<scenario>",
"variant_id":"<variant>",
"raw_artifacts":{
"loadgen_output":"loadgen-output.json",
"service_log":"service.log",
"runtime_log":"runtime.log",
"runtime_trace":"runtime-trace.dat"
},
"normalization_inputs":{
"throughput_source":"loadgen_output",
"latency_source":"loadgen_output",
"startup_source":"service_log",
"runtime_diagnostics_source":"runtime_trace"
}
}
This example shows the minimum traceability we want: raw artifacts are archived, the mapping to normalized metrics is explicit, and optional Java telemetry is supported without making the whole dataset JVM-specific.
Our canonical dataset keeps one repeated run inspectable end to end by linking scenario and variant metadata, environment details, raw artifacts, analysis windows, derived metrics, and validation status in one normalized record.
How repeated runs become reported comparisons
This is the point where many benchmark posts quietly switch from measurement to rhetoric.
Our aggregation path is strict:
run -> cell -> scenario and variant comparison
That means one run never becomes a headline by itself. A run belongs to a repeat set. Accepted repeats are aggregated into a cell. Cells are compared only within the same scenario boundary.
So if you are looking at one workload scenario, the comparison is between variants within that scenario. We are not allowed to blend unlike scenarios into one runtime score. That would answer no coherent engineering question.
We also summarize metric families separately.
Startup and readiness stay separate because they answer, “How quickly can this process become usable?” In this series, startup and readiness are only comparable when they come from the same per-run lifecycle defined in the benchmark protocol. We do not mix fresh-process startup measurements with reused-process steady-state repeats and call them one startup story.
Warmup behavior stays separate because it answers, “How quickly does this runtime shape settle?” Steady-state throughput stays separate because it answers, “How much work is delivered once the run reaches its main measurement phase?” Latency percentiles stay separate because tail behavior is not interchangeable with throughput. CPU efficiency and memory footprint are separate again because resource cost is part of the runtime shape, not background noise. Runtime diagnostics such as GC logs or Java Flight Recorder traces stay contextual and explanatory rather than turning into a hidden deciding factor.
That leads to one rule worth stating plainly:
We do not treat throughput, tail latency, CPU, memory, runtime diagnostics, and startup as one scoreboard.
In practice, that means later figures and captions should compare like with like: throughput against throughput, latency against latency, startup against startup, and resource-cost metrics in their own views.
Why be so strict? Because composite benchmark scoring hides tradeoffs the reader actually cares about. A variant can start faster and still have weaker steady-state throughput. Another can deliver stronger throughput and still consume more CPU per unit of work. A third can look strong on average and still have a wider p99 spread. Those are not contradictions. They are different dimensions of runtime behavior.
For the Java side, this matters even more if multiple Java runtime shapes appear. The Helidon-based benchmark variant is one Java framework shape, not “Java” as a whole. If the series later includes another JDK-based workflow with different startup or warmup behavior, that remains its own variant. The analysis contract forbids us from pooling unlike runtime modes into one Java bucket and then talking as if the combined number represents the platform fairly.
In practical terms, a reported comparison in the results article might say that one variant shows higher steady-state throughput in a given scenario while another reaches readiness sooner or stabilizes earlier in warmup. That is allowed. Saying one of them “wins overall” is not.
How we handle invalid runs, excluded repeats, and unstable cells
A benchmark result is not just a number. It is also an accounting of how much evidence survived long enough to support that number.
Every reported cell summary needs to make four things visible:
total repeats attempted
repeats accepted
repeats excluded by reason class
a central value plus a visible uncertainty or instability signal for the reported metrics
If a cell is unstable, that needs to be visible too. If telemetry is incomplete for one metric family, that should show up as a missing slice, not vanish into silence. That does not always mean the whole run is invalid. Missing optional telemetry may leave a run usable for core throughput and latency reporting while making it unavailable for a diagnostic metric family. Missing required comparison artifacts is a different case and can invalidate the run entirely under the series acceptance rules.
Here is an illustrative cell-summary example showing the reporting shape we expect. The interval fields here show reporting shape only; they do not prescribe a specific statistical method by themselves.
{
"cell_id":"<scenario>/<variant>",
"runs_attempted":8,
"runs_accepted":6,
"runs_excluded":2,
"exclusion_reason_counts":{
"startup_failure":1,
"artifact_incomplete":1
},
"reported_metrics":{
"throughput_rps_median":39480.0,
"throughput_rps_interval":[38990.0,39910.0],
"latency_p99_ms_median":9.9,
"latency_p99_ms_interval":[9.1,11.4],
"rss_mb_median":608,
"rss_mb_interval":[601,620]
},
"stability_flags":[
"moderate_tail_variance"
],
"notes":[
"steady-state metrics computed only from accepted runs",
"excluded runs remain visible in the published summary"
]
}
This is a small example, but it carries the full contract.
First, it tells you how many times we tried. That matters because “median of six accepted runs” means something different when it came from six attempts versus eight attempts with two exclusions.
Second, it tells you what got excluded and why. A startup failure and an incomplete artifact are not the same problem, and they should not disappear behind a cleaned-up summary.
Third, it reports uncertainty signals alongside central values. We are not going to publish a tiny difference in throughput or p99 and pretend the reader should treat that as settled truth without any variation context. Repeated benchmark runs vary, and the summary needs to make that visible.
Fourth, it can flag instability even when the cell is still worth showing. An unstable cell is not automatically worthless. It is a sign that the claim attached to it needs to stay narrow.
Here is how we want a human reader to interpret that example:
Attempted eight repeats. Accepted six. Excluded two, and the reasons are visible. The reported throughput and p99 come only from accepted runs. Tail behavior still varies enough that we should not use this cell as the basis for sweeping claims.
There is also a small-sample rule underneath all of this. This article fixes the reporting shape, not the full statistical appendix, but later results still need to meet a minimum bar: if a metric is compared, the chart or adjacent caption must show accepted-repeat counts and some visible uncertainty or instability signal for that metric family. If accepted evidence is too thin for a normal cell summary, we mark the cell as insufficient evidence instead of presenting it as a clean head-to-head result. If a cell does not meet the series minimum for comparability, it may still be shown as incomplete evidence, but not as a claimed winner.
This article keeps invalid runs, accepted counts, and uncertainty visible, but load-generator validity questions such as coordinated-omission handling must be documented separately in the series methodology and tool configuration.
A reported cell summary shows how many repeats we attempted, how many were accepted, why any were excluded, which metrics are summarized, and whether instability limits strong claims.
Which uncertainty signals we report and why
Uncertainty is part of the result, not a footnote.
A point estimate by itself is easy to quote and easy to overread. That is exactly why later articles need more than a single median, average, or percentile value in isolation. Repeated runs vary even when the benchmark protocol is stable, so the published comparison has to carry some visible signal of that variation.
Our reporting rule is simple:
each compared metric family needs a central summary value
each compared metric family also needs a visible uncertainty or instability signal
accepted-repeat counts must stay close to the reported value
excluded-repeat counts and reasons remain visible at the cell level
That does not mean every figure turns into a statistics lecture. It means the reader should be able to tell whether a small gap is supported by stable repeated evidence or sits inside a noisy range that weakens the claim.
It also means we are careful with what interval language implies. An interval estimate is not proof. It is a compact way to show that repeated measurements vary and that narrow or wide spread changes how strongly we should read the comparison.
This article fixes the reporting shape, not the exact interval formula. The results article needs to name one series-wide method and apply it consistently across compared cells. The same applies to instability thresholds: they need one published rule for the series, not case-by-case judgment after the numbers are visible.
The practical effect is straightforward: later result claims can be stronger when accepted repeats are stable and uncertainty is tight, and narrower when the cell remains noisy or partially incomplete.
Which plots are allowed for each metric family
Plot choice is part of the method. It is not decoration added after the data already “speaks for itself.”
Different metric families need different chart shapes because they answer different questions.
Throughput comparisons work well as bars or points with visible uncertainty because the reader needs a direct side-by-side view and a clear sense of whether small gaps are likely meaningful.
Latency tails need tail-aware views. Percentile lines or tail-focused point comparisons are appropriate because p95 and p99 behavior should stay visible instead of being flattened into one average-latency story.
Startup and readiness need timeline or phase-duration views. A startup chart should not sit on the same visual axis as steady-state throughput because those are unlike quantities answering unlike questions.
Warmup behavior needs time-series views. That is the honest way to show convergence, early instability, or time-to-peak differences.
CPU efficiency is better served by scatter or normalized views that pair delivered work with CPU cost. Raw CPU percentages alone are often too context-poor.
Memory footprint works as bars or points with intervals, as long as it is not mixed into a composite throughput-latency-resource scoreboard.
Just as important, some chart patterns are off-limits in this series because they mislead more than they clarify.
We will not use stacked bars that imply throughput, latency, CPU, and memory add up to one thing. They do not.
We will not use mixed-axis mashups that visually dramatize one metric by scaling another into the background.
We will not publish a single scoreboard that combines startup, p99 latency, throughput, CPU, memory, and runtime diagnostics into one rank.
And we will not hide exclusions or uncertainty in figure notes while putting the cleanest-looking number in the chart title.
We choose plot types by metric family so readers can inspect throughput, tail latency, startup, warmup, CPU efficiency, and memory behavior without collapsing unlike measures into one score.
What later articles will and will not be allowed to claim
By this point, the contract should feel narrow enough to be useful.
The results article may compare variants within defined scenario and cell boundaries. It may say that one variant showed higher steady-state throughput for a given scenario. It may say another reached readiness sooner. It may say a variant’s p99 interval was tighter or that a cell remained unstable enough to weaken the claim. It may use Java runtime telemetry as explanatory context when the artifact trail supports it. For example, GC logs or Java Flight Recorder data can help explain whether tail disturbances align with runtime events instead of leaving the reader with a vague runtime story.
But later articles may not do several tempting things.
They may not declare an overall language winner.
They may not merge startup, throughput, tail latency, CPU, and memory into one ranking.
They may not hide invalid or excluded runs just because the accepted set tells a cleaner story.
They may not generalize from the benchmarked Java framework variant to all Java frameworks, or from a Go service built on net/http to Go as a whole.
They may not treat separately benchmarked JDK distributions as interchangeable just because they are closely related upstream. Even when two JDK distributions are derived from OpenJDK source, separately benchmarked distributions remain separate variants for reporting.
They may not treat a JVM run, a native image, a checkpoint-and-restore workflow, or any other materially different runtime path as the same thing just because they come from related tooling or source bases.
A short way to remember the rule is this:
Allowed claim: “Within this scenario, variant A shows higher steady-state throughput, while variant B reaches readiness sooner and shows a tighter p99 interval.”
Disallowed claim: “Variant A wins overall.”
That line may sound strict, but it is the difference between a benchmark that helps engineering decisions and one that mostly fuels argument.
What changes after this article
Up to now, the series established the benchmark scope, the service contract, the implementation shapes, the load-generation logic, the run protocol, and the reproduction path. What changes here is that the analysis rules are now fixed.
That matters because once results appear, readers should not have to reverse-engineer the logic behind each figure. You should already know what a cell is, what the canonical dataset carries, how accepted runs are aggregated, what exclusions look like, why startup and steady state stay separate, and why no one score is coming to rescue a complicated comparison.
You should also know what this article does not settle. Keeping exclusions and uncertainty visible improves the honesty of the reporting, but it is not a substitute for tool-specific load-generator behavior, runtime-specific diagnostics, or careful host-environment disclosure. Those still need to appear where the benchmark evidence is published.
If you are the kind of reader who distrusts benchmark posts by default, this is the article that should make the next one easier to read. Not because it proves any runtime is better, but because it limits what we are allowed to claim when the numbers arrive.
So when you read the results article, read it with this contract in mind. Ask whether every chart stays inside a scenario boundary. Ask whether exclusions and accepted counts are visible. Ask whether uncertainty is shown where the article wants you to care about a difference. And ask whether the interpretation respects the fact that startup, warmup, throughput, latency, CPU, memory, and runtime telemetry are related signals, not one giant score.
That is the discipline this series needs if the conclusions are going to be worth anything.
Conclusion
Benchmark trust is easy to lose because the final chart compresses a lot of judgment into one visual. This article makes those judgments explicit before the results article gets a chance to hide them.
Our analysis contract is simple to state even if it takes work to follow. We normalize each run into a canonical record. We keep raw artifacts linked to derived metrics. We validate runs and keep excluded ones visible by reason class. We aggregate accepted repeats into scenario and variant cells. We report metric families separately. We show uncertainty and instability instead of pretending they are background noise. And we forbid composite-score storytelling.
That does not make the later results automatically correct. It does make them much harder to overclaim.
In the next article, we apply this contract to the actual benchmark outputs. The important part is that the rules are already on the page.
]]>https://redstack.dev/2026/10/30/how-we-analyze-benchmark-data-before-claiming-anything/feed/04881Reproduce the Go net/http and Java Helidon SE Benchmark Environment from Source
https://redstack.dev/2026/10/28/reproduce-the-go-net-http-and-java-helidon-se-benchmark-environment-from-source/
https://redstack.dev/2026/10/28/reproduce-the-go-net-http-and-java-helidon-se-benchmark-environment-from-source/#respondWed, 28 Oct 2026 16:03:00 +0000https://redstack.dev/?p=4876Continue reading →]]>Key Takeaways
A benchmark result is only useful if another engineer can inspect the source package, rerun the command path, and review the generated artifacts. Reproducibility comes before interpretation.
This package treats the Go net/http service and the Java Helidon SE service symmetrically at the harness level. Both are built from source through package scripts, validated against the same public contract, and expected to write evidence under the same artifact tree.
The run manifest is the main handoff artifact for this package. It connects toolchain versions, service configuration, validation status, matrix configuration, and generated file locations so later analysis can trace supported claims back to the run artifacts that support them.
This article covers benchmark execution and reproduction. It does not compare latency, throughput, resource use, language superiority, or Oracle AI Database performance.
Service-runtime choices matter when an HTTP endpoint sits in front of a model call, retrieval step, vector search request, enrichment pipeline, or another application workload. Teams naturally ask whether Go, Java, framework choice, JDK choice, warmup, or runtime configuration will change the shape of that service under load.
Before any performance chart deserves attention, though, the artifact behind it has to be runnable.
That is the job of this article.
In this part of the single-machine benchmark series, we move from design to execution. Earlier articles defined the benchmark goals, service contract, Go implementation shape, Java Helidon SE implementation shape, load-generator design, and run methodology. Here we start from the benchmark source package, run the prerequisite and validation gates, build both services, run the benchmark matrix, and inspect the artifacts that later articles will analyze.
This is not the results article. It is the reproduction article.
This reproduction path is scoped to a local Linux environment using Bash and the package scripts. Other environments, including macOS, Windows, WSL, containers, and CI runners, may work only where the package explicitly documents and validates them.
Version basis: the command path and sample output reflect the package layout used for this article, so script wording, manifest field names, artifact names, and dependency versions can vary by package release.
What this article helps you reproduce
The benchmark source package is the unit of trust. Not a chart. Not a slide. Not an isolated binary. The package includes the Go service source, the Java Helidon SE service source, shared contracts, fixtures, scripts, package-local tooling, manifest templates, and artifact directories. The reproduction run writes generated evidence under artifacts/.
In this walkthrough, we use the package-root command path to show:
Where the source files, contracts, fixtures, and scripts live.
How to verify the local Linux/Bash environment before building anything.
How to capture toolchain and host facts.
How to validate the shared service contract.
How to build both services from source.
How to run smoke checks on loopback.
How to execute the benchmark matrix without publishing benchmark numbers.
How to inspect the run manifest and generated artifacts.
The package root is the top-level directory of the materialized benchmark source package. In this package, it is the directory containing scripts/, contracts/, fixtures/, services/, tools/, manifests/, and artifacts/.
Run every command in this article from the package root unless a section says otherwise. The validation scripts load contract files relative to that root, and the benchmark scripts write generated evidence into the package’s artifacts/ tree.
If a command is run from the wrong directory, the scripts fail fast rather than silently loading a different contract or writing artifacts somewhere unexpected. That is deliberate. The working directory is part of the reproduction contract.
We reproduce the benchmark by moving from the source package through prerequisite checks, environment capture, validation, builds, smoke checks, matrix execution, artifact capture, and manifest review before interpreting any results.
What this article does not claim
This article does not compare Go and Java latency. It does not compare throughput. It does not compare CPU use, memory use, garbage collection behavior, JDK distributions, or deployment cost. It does not say one language is better than the other.
It also does not measure Oracle AI Database performance. This package validates the benchmark execution harness. If another benchmark slice adds an Oracle AI Database dependency, that slice needs its own driver configuration, credential handling, manifest fields, validation gates, and scope statement.
For this article, a good run is not a fast run. A good run is one where the package builds, validates, executes, and captures evidence without skipping a gate.
Source package layout
Start by orienting yourself in the package. The first command is not a build. It is a quick check that you are standing in the right place.
pwd
find . -maxdepth2-type d | sort
The top-level shape should look like this:
.
./artifacts
./artifacts/benchmark
./artifacts/env
./artifacts/logs
./artifacts/manifests
./artifacts/validation
./contracts
./docs
./fixtures
./fixtures/errors
./fixtures/valid
./manifests
./scripts
./services
./services/go-http
./services/java-helidon
./tools
./tools/benchctl
The Go implementation is intended to use Go’s standard-library net/http package, with its service entry point under services/go-http/cmd/server/.
The Java service lives under services/java-helidon/. It is a Helidon SE service, with its Helidon version pinned in services/java-helidon/pom.xml. The Java build packages the service JAR and runs it with the classpath resolved by the package’s Maven build.
The shared service contract lives at contracts/work-contract.json. The valid and error fixtures live under fixtures/valid/ and fixtures/errors/. The package-local benchmark and contract tooling lives under tools/benchctl/, so the orchestration path is inspectable as source.
Generated evidence goes under artifacts/. That includes environment facts, validation output, service logs, benchmark matrix output, and manifests.
The split matters. Source inputs and generated evidence need to be easy to separate. Later analysis should be able to connect a supported claim to a manifest, validation output, generated file, or log instead of relying on memory or console scrollback.
Step 1: Verify prerequisites
Run the prerequisite check before you build or launch either service.
./scripts/check-prereqs.sh
A successful run should include these categories of checks and end with a PASS result. Exact log wording can vary by package version:
[check-prereqs] package root: PASS
[check-prereqs] Go toolchain: PASS
[check-prereqs] Java runtime: PASS
[check-prereqs] Java compiler: PASS
[check-prereqs] Maven command: PASS
[check-prereqs] required scripts: PASS
[check-prereqs] contracts directory: PASS
[check-prereqs] artifacts writable: PASS
[check-prereqs] result: PASS
This step checks that the expected commands and paths are visible from the package root. It looks for tools such as Bash, Go, java, javac, Maven, curl, and common Linux utilities used by the scripts. It also verifies required package paths such as contracts/work-contract.json, fixtures/, services/go-http/, services/java-helidon/, and tools/benchctl/.
The prerequisite check is a preflight gate, not a full build. If the package does not vendor all dependencies, the Java build needs access to the configured Maven repositories or a pre-populated local Maven cache, and the Go build needs access to any required Go modules or a pre-populated Go module cache. Dependency-resolution problems usually become visible at the later build gates.
A passing prerequisite check means the package can start the reproduction path. It does not mean the benchmark is valid, and it does not mean the Java and Go services are behaviorally comparable. Those claims require later gates.
Helidon 4 requires Java 21 or later. The prerequisite check records the Java commands it finds; the Java build and runtime validation gates still have to pass.
Step 2: Capture environment facts
Benchmarks become hard to trust when the environment is described from memory. The package records environment facts before the benchmark matrix runs.
./scripts/capture-env.sh
A successful run writes environment and manifest files and ends with a PASS result. The output should include files in these categories:
[capture-env] wrote artifacts/env/go-version.txt
[capture-env] wrote artifacts/env/java-version.txt
[capture-env] wrote artifacts/env/javac-version.txt
[capture-env] wrote artifacts/env/os-release.txt
[capture-env] wrote artifacts/manifests/environment-manifest.json
[capture-env] result: PASS
Now inspect the files that were created:
find artifacts -maxdepth3-type f | sort
At this point you should see environment files like these:
artifacts/env/architecture.txt
artifacts/env/cpu.txt
artifacts/env/go-version.txt
artifacts/env/java-version.txt
artifacts/env/javac-version.txt
artifacts/env/kernel.txt
artifacts/env/maven-version.txt
artifacts/env/memory.txt
artifacts/env/os-release.txt
artifacts/manifests/environment-manifest.json
The environment manifest records toolchain and host facts used by a specific benchmark execution. It does not try to be a complete machine inventory. It records the facts that matter to reproduction: Go version, Java runtime version, Java compiler version, Maven version, OS and kernel details, architecture, CPU summary, memory summary, package version, and the package-local tool version when that tool has already been built.
Record the exact JDK distribution, version, and build string from java -version, not only the Java feature version. JDK distribution and build details are benchmark inputs, just like the Go version, framework configuration, warmup settings, and JVM arguments supplied through JAVA_SERVICE_JVM_ARGS.
That is enough for the next engineer to ask useful questions. Did the run use a different JDK? Was the Go version different? Did the architecture change? Were JVM arguments supplied? Those are not trivia. They are benchmark inputs.
Environment capture explains where the benchmark ran. It does not make a single-machine run representative of every deployment shape.
Step 3: Validate the shared contract
Before we build confidence in any measurement, both services have to satisfy the same behavioral contract.
The contract defines GET /health, HEAD /health, and POST /work. The /work endpoint accepts application/json with four required fields: requestId, payloadSize, seed, and extraWork. Validation is intentionally strict. The decoded request body is limited to 4096 bytes, requestId must be a string with length 1..128, payloadSize must be an integer in the range 0..131072, seed must be an integer in the range 0..2147483647, and extraWork must be an integer in the range 0..100.
Successful /work responses return requestId, payloadSize, extraWork, checksum, and ok. The validators also reject unknown fields, duplicate fields, missing required fields, scalar type violations, quoted numeric strings, numeric bound violations, invalid JSON, multiple JSON documents, and decoded bodies larger than 4096 bytes.
Run the contract wrapper from the package root:
./scripts/validate-contract.sh
A successful run should show the Go service checks, the Java Helidon SE service checks, and the equivalence cases all passing:
This wrapper does more than inspect source files. It runs the package’s unit and tool checks, builds the services as needed, starts both services on loopback, and uses the package-local contracttest command to compare responses across the shared fixtures.
That is the important part: equivalence is tested against the package contract, not assumed.
The Go and Java implementations are allowed to be different internally. They use different languages, different runtime models, and different libraries. But before the benchmark matrix runs, they need to agree on the external behavior defined by the contract.
Because this validation starts live services on loopback, make sure the package’s validation ports are available before running it. If validation fails with a bind or connection error, stop any stale service process first, then rerun the validation command. Use alternate port variables only where the package scripts explicitly document support for them.
If this step fails, stop. Fix the implementation, fixture, or environment problem first. A downstream benchmark run after a failed contract gate is not comparable evidence.
Step 4: Build the Go and Java services
Now build both benchmark service implementations from the package source.
Start with Go:
./scripts/build-go.sh
A successful Go build runs the configured checks and writes the service binary:
[build-go] checking module
[build-go] building service
[build-go] wrote bin/go-http-server
[build-go] result: PASS
The point is not that Go can produce a binary. The point is that this package does not ask you to trust a prebuilt benchmark service. The service used by the benchmark is built through the same package-root path every time.
Now build the Java Helidon SE service:
./scripts/build-java.sh
A successful Java build resolves dependencies, compiles the service, runs tests, and packages the JAR:
[build-java] resolving Java build
[validate-java] resolving Java build
[validate-java] compiling main sources
[validate-java] compiling tests
[validate-java] running tests
[validate-java] packaging Java Helidon SE service
[validate-java] wrote services/java-helidon/target/java-helidon-benchmark.jar
[validate-java] result: PASS
[build-java] wrote services/java-helidon/target/java-helidon-benchmark.jar
[build-java] result: PASS
The Java build resolves the Helidon dependencies, compiles the service, compiles and runs the Java tests, and packages services/java-helidon/target/java-helidon-benchmark.jar.
One naming detail matters here: this is the Java Helidon SE implementation used in this benchmark package. It is not a claim about every Java framework or every JVM configuration. A Spring Boot service, Quarkus service, Micronaut service, GraalVM Native Image build, or a different Helidon configuration would be a different benchmark artifact.
This article’s command path runs the Java Helidon SE service on the configured JDK. It does not invoke a GraalVM Native Image build. If a package version adds Native Image support, that should be treated as a separate benchmark artifact and recorded separately.
Step 5: Start the services and run smoke checks
Build success is not enough. We also want a fast operational check that both services can start, bind to loopback, answer /health, answer a basic /work request, write logs, and stop cleanly.
Run the smoke script:
./scripts/run-smoke.sh
By default, the script uses 127.0.0.1:18180 for the Go service and 127.0.0.1:18181 for the Java Helidon SE service. You can override those with GO_SERVICE_PORT and JAVA_SERVICE_PORT if your local machine already has something on those ports.
A successful smoke run should show both services becoming ready, passing a request check, and stopping cleanly:
[smoke-go] ready: http://127.0.0.1:18180/health
[smoke-go] request: PASS
[smoke-java] ready: http://127.0.0.1:18181/health
[smoke-java] request: PASS
[smoke-go] stopped
[smoke-java] stopped
[smoke] result: PASS
If you need alternate ports for the smoke check, pass them explicitly:
Smoke checks are not load tests. They are a safety gate before the benchmark matrix runs.
The logs from this step are written under artifacts/logs/, and the smoke validation file is written under artifacts/validation/smoke-validation.json. Those files matter because a later failed artifact verification should tell you whether the problem happened before, during, or after service launch.
Step 6: Run the benchmark matrix
The benchmark matrix is the configured set of benchmark executions for this package. It defines which service runs, which workload settings apply, and which artifacts the runner should capture.
Now run the matrix command, but keep the scope clear: this article still does not publish benchmark results.
./scripts/run-matrix.sh
A successful matrix run should show the matrix loading, each service being prepared and captured, the manifest being generated, and the final result passing:
[run-matrix] loaded benchmark matrix
[run-matrix] prepared Go service run
[run-matrix] captured Go service artifacts
[run-matrix] prepared Java Helidon SE service run
[run-matrix] captured Java Helidon SE service artifacts
[generate-manifest] wrote artifacts/manifests/run-manifest.json
[generate-manifest] result: PASS
[run-matrix] wrote run manifest
[run-matrix] result: PASS
The default package matrix is intentionally small. Its job in this article is to prove orchestration and artifact capture: start one service, run the package-local benchctl tool against it, capture the output, stop it, repeat symmetrically for the other service, and write a run manifest.
benchctl is package-local orchestration tooling for this demo package. It is not being presented here as a general-purpose load-testing standard or as a substitute for a production benchmark methodology. This article does not claim that benchctl avoids coordinated omission or is suitable for production-grade latency analysis; those properties would need to be documented and validated before using its output for latency conclusions.
This local matrix is useful for proving orchestration and artifact capture. It is not evidence that the same behavior will appear on another host, container runtime, kernel configuration, cloud shape, or production deployment.
That design keeps this article focused. The matrix step produces data for later analysis. Here we prove that the run can be executed and captured; we do not interpret the generated files as performance results.
If you need the matrix run to use nondefault service ports, pass the port variables to the matrix command as well:
A partial matrix run is not comparable benchmark evidence. If the Go side completes and the Java side fails, or if the matrix runs but the manifest is missing, you do not have a valid run. You have a failed run with useful diagnostic artifacts.
Step 7: Inspect generated artifacts
After the matrix runs, verify the expected artifact set:
./scripts/verify-artifacts.sh
The verifier should report each required artifact category as present:
After a successful run, the artifact tree should include files like these, with the generated run manifest acting as the source of truth for the exact artifact set:
artifacts/benchmark/go/go-summary.json
artifacts/benchmark/java/javaHelidon-summary.json
artifacts/env/go-version.txt
artifacts/env/java-version.txt
artifacts/env/javac-version.txt
artifacts/logs/go-build-output.txt
artifacts/logs/go-service.log
artifacts/logs/java-build-output.txt
artifacts/logs/java-service.log
artifacts/manifests/environment-manifest.json
artifacts/manifests/run-manifest.json
artifacts/validation/contract-validation.json
artifacts/validation/equivalence-validation.json
artifacts/validation/smoke-validation.json
The package separates source inputs from generated evidence so later analysis can trace supported claims back to contracts, scripts, validation output, logs, benchmark files, and manifests.
The first artifact to inspect is the run manifest.
cat artifacts/manifests/run-manifest.json
The run manifest is the benchmark execution record. It is intended to connect the package version, service configuration, toolchain facts, matrix configuration, and artifact locations for a specific run.
The exact manifest fields are defined by the package release you run. For this package, the generated manifest should describe the run identity, package version, service configuration, toolchain facts, matrix configuration, and artifact locations.
A shortened manifest excerpt has this general shape:
{
"runId":"run identifier generated by the package",
"package":{
"version":"package version recorded during the run",
"root":"package root recorded during the run"
},
"services":{
"go":{
"runtime":"Go version recorded during the run",
"binary":"bin/go-http-server",
"port":18180
},
"javaHelidon":{
"helidonVersion":"Helidon version recorded during the run",
Use the generated manifest, not this abbreviated excerpt, as the source of truth for later analysis.
The manifest is the bridge between reproduction and analysis. It tells later articles which package version ran, which Go and Java runtimes were recorded, which service ports were used, where the matrix configuration came from, and where to find the validation and benchmark artifacts.
It does not say which implementation is faster. It tells you how the run was produced.
What counts as a valid run
A valid run is a benchmark execution where every required gate completes and the generated artifacts match the run manifest.
For this package, a valid run means:
The prerequisite check passes.
Environment facts are captured.
Shared contract validation passes.
Live Go-versus-Java equivalence validation passes.
Both services build from the package source.
Smoke checks pass for both services.
The benchmark matrix completes for both services.
Artifact verification passes.
The environment and run manifests exist.
The manifest paths match the generated artifact tree.
That definition may sound strict, but it prevents a common benchmark failure mode: treating partial output as if it were comparable evidence.
If a build fails, you do not have a benchmark. If contract validation fails, you do not have a fair comparison against this package contract. If the matrix runs but the manifest is missing, you do not have an auditable run. If artifact verification fails, later analysis should not use that run.
What to rerun when validation fails
When a gate fails, stop at the failed gate. Do not keep running commands in the hope that later output will be useful.
If the package root is wrong, go back to the directory containing scripts/, contracts/, fixtures/, services/, and tools/, then rerun the prerequisite check:
./scripts/check-prereqs.sh
If environment capture fails, fix the writable artifact path or missing tool problem, then rerun:
./scripts/capture-env.sh
If contract validation fails, fix the implementation or fixture mismatch, then rerun:
./scripts/validate-contract.sh
If smoke or matrix execution fails because generated artifacts from an earlier attempt are confusing the run boundary, the package includes a cleanup script for generated run artifacts:
./scripts/clean-run.sh
A successful cleanup prints output in this shape:
[clean-run] removed generated run artifacts
[clean-run] clean boundary ready
This cleanup step removes generated run evidence. It is not a process manager. If a service is still running or a loopback port is occupied, stop that process or choose documented alternate ports before rerunning the smoke or matrix command.
Then restart from a clean boundary:
./scripts/check-prereqs.sh
./scripts/capture-env.sh
./scripts/validate-contract.sh
The important rule is simple: do not merge artifacts from failed and successful attempts. Keep each run’s evidence coherent, or discard it and rerun.
How this connects to later analysis
This reproduction run produces the evidence path that the remaining articles need.
The next article explains how generated data can be normalized, aggregated, modeled, and visualized. The results article presents benchmark results from valid runs. The final interpretation article discusses what those results mean for runtime choice, service design, and operational tradeoffs.
The order matters. Without this reproduction step, later charts would ask readers to trust an invisible process. With it, the process is inspectable: source, scripts, contracts, manifests, logs, validation output, and benchmark artifacts all live in the package.
That is how a benchmark earns the right to be discussed.
A reproducible benchmark starts before the first chart. It starts with a source package that another engineer can inspect, a command path that can be rerun, validation gates that fail loudly, and artifacts that connect later analysis back to the run that produced them.
In this article, we reproduced the Go net/http and Java Helidon SE benchmark environment from the package root. We checked prerequisites, captured environment facts, validated the shared contract, built both benchmark service implementations from package source, ran smoke checks, executed the matrix, and inspected the generated manifests and artifacts.
That gives the rest of the series a stable foundation. The next step is not to declare a winner. The next step is to use the generated evidence carefully, so any later result can be traced back to a valid, auditable run.
]]>https://redstack.dev/2026/10/28/reproduce-the-go-net-http-and-java-helidon-se-benchmark-environment-from-source/feed/04876The Benchmark Methodology Behind This Series
https://redstack.dev/2026/10/26/the-benchmark-methodology-behind-this-series/
https://redstack.dev/2026/10/26/the-benchmark-methodology-behind-this-series/#respondMon, 26 Oct 2026 16:01:00 +0000https://redstack.dev/?p=4866Continue reading →]]>Key Takeaways
This article defines the measurement contract before any result charts appear. Later comparisons only count if another engineer can inspect the setup, challenge the controls, and reproduce the run.
The real comparison unit is a benchmark cell, not a label like “Go” or “Java.” A cell includes the service shape, runtime and execution mode, payload, concurrency, CPU and memory controls, telemetry profile, and repeat identity.
Startup, readiness, warmup, measurement, and artifact capture stay separate. We do not blend early-runtime behavior into steady-state numbers or hide discarded runs behind vague “outlier” language.
CPU counts are only meaningful when the enforcement mechanism and host controls are visible. Governor state, boost behavior, core placement, and load-generator headroom belong in the result package, not in a footnote.
If you have ever read a benchmark post and thought, I still can’t tell whether this is a runtime result or a harness result, this article is for you.
That confusion usually starts long before the chart. A bar labeled “Java” hides multiple runtime shapes. A CPU limit is given as a number, but not the mechanism that enforced it. Warmup gets blended into steady-state measurement. A few awkward runs disappear behind a line like “we removed outliers.” The numbers may be real, but the method is too loose to support the confidence the article projects.
We want to fix that before we publish a single result chart.
This article defines the run protocol for the rest of the series. It is the measurement contract for how we compare a small Go net/http service with a Helidon SE service on a specifically identified JDK and execution mode. It defines what a benchmark cell is, how warmup and measurement are separated, what host controls must be visible, what makes a run invalid, what telemetry every accepted run needs, and what artifacts must survive for reproduction. It does not present benchmark results.
One scope note up front: this series compares specific service and runtime shapes implemented in Go and Java, not the languages in the abstract. On the Java side, the comparison unit is Helidon SE on a named JDK and execution mode, not a generic “Java” bucket. On the Go side, the comparison unit is a small net/http service, not “all Go.” If later articles add a virtual-thread configuration, a startup-optimized Java mode, or another execution mode, each one will be treated as its own benchmark condition with its own startup, warmup, artifact, and reproducibility requirements.
Why methodology is part of the result
Benchmark methodology is not background detail. It is part of the result.
That matters even more in a series framed around Go and Java because readers bring strong priors. Some expect Go to win simple HTTP work by default. Some expect virtual threads to affect Java concurrency tradeoffs in certain server designs. Some assume framework choice matters more than language choice. We also see benchmark writeups collapse JDK distribution and execution mode differences into a single “Java” label. A few of those ideas may prove partly true under some conditions. None of them should get a free pass over measurement.
The runtime shapes in this series are easy to overread if we are sloppy. A small Go net/http service is not “all Go.” A Helidon SE service on a named JDK is not “all Java.” If the benchmark protocol fails to keep those differences visible, the charts will look more certain than they deserve.
That is why we are publishing the protocol before the charts. We want you to see the controls first, then the numbers.
The benchmark contract in one pass
Here is the short version.
A benchmark cell is the real unit of comparison. It includes the runtime variant, execution mode, payload profile, concurrency, CPU allocation method, memory limit, telemetry profile, and repeat ID. A warmup window is the period used to let runtime behavior settle before measurement. A measurement window is the only period whose data is eligible for later steady-state charts. An invalid run is a run excluded because the benchmark contract was broken: preflight failed, readiness never stabilized, warmup bled into measurement, required artifacts went missing, host state drifted, or the load generator became the bottleneck. An artifact manifest is the durable record of versions, host state, telemetry, and outputs required to inspect or reproduce the run.
Host state is a prerequisite, not an afterthought, so governor mode, turbo or boost status, CPU allocation method, and service-versus-load-generator placement must be recorded before measurement starts. Run order is controlled to reduce time drift, thermal drift, and first-run bias. Invalid runs are rejected by rule rather than by taste. Telemetry is mandatory because throughput and latency alone are not enough to explain a run. Later charts aggregate accepted runs only, while excluded runs stay visible in the raw records with an explicit reason.
We separate preflight, readiness, warmup, measurement, teardown, cooldown, and artifact capture so later charts describe steady-state runs rather than blended startup behavior.
That summary is intentionally strict. The rest of this article explains why each rule exists and what it protects.
What counts as a benchmark cell
A benchmark cell is the smallest comparison unit that still means something. If two runs differ in a way that could affect the result, they belong in different cells.
That sounds obvious, but benchmark articles often violate it with labels that are too broad. “Go” is not a cell. “Java” is not a cell. Even “Helidon SE” is not a cell. A useful benchmark cell has to name the workload shape, the runtime shape, and the host-control assumptions that made the run possible.
Here is the shape we mean:
benchmark_cell:
app_variant: hello-api-json
language_runtime: java
framework_mode: helidon-se
execution_mode: hotspot-jit
runtime_distribution: named-distribution
runtime_version: named-version
cpu_allocation_method: declared-method
cpu_allocation_value: declared-value
memory_limit: declared-limit
payload_profile: json-small
concurrency: 64
warmup_duration:"30s"
measurement_duration:"60s"
cooldown_duration:"20s"
telemetry_profile: baseline
repeat_id: 03
host_control_state:
governor: documented
turbo_boost: documented
loadgen_placement: documented
This is not the final manifest format for the execution article, but it captures the important idea: a benchmark cell includes more than the application binary or the language name. It includes the execution mode, the CPU-shaping method, the payload, the telemetry profile, and the repeat identity.
That matters because later analysis depends on those boundaries being real. If we quietly average together runs that differ in CPU mechanism, warmup duration, execution mode, or telemetry overhead, we are not summarizing one condition. We are averaging unlike things and hoping the label hides the damage.
A benchmark cell also gives us a cleaner way to disagree. If you think the CPU limit was wrong, or the telemetry profile was too heavy, or the execution mode was not representative, you can point to a named dimension of the benchmark cell instead of arguing with a vague bar in a chart.
A benchmark cell is the irreducible comparison unit. Runtime, execution mode, payload, concurrency, CPU allocation, telemetry profile, and repeat identity all belong in the cell definition.
How one measured run actually works
A measured run is not “start service, fire load, record requests per second.” It is a controlled sequence with explicit phase boundaries.
For this series, one measured run moves through these stages:
host preflight
service startup
readiness gate
warmup window
measurement window
runtime and load artifact capture
teardown
cooldown
Those boundaries exist because startup, warmup, and steady state answer different questions. Startup tells us when the service becomes usable. Warmup tells us how the runtime settles. The measurement window is the only part that belongs in later steady-state charts. If we collapse those phases together, we lose interpretability first and only later notice that we also lost trust.
The host preflight phase records the host assumptions before the run starts. If we cannot show what CPU-limiting mechanism, governor mode, or memory shape was actually in effect, we do not have a reliable basis for comparison.
The readiness gate is not warmup. The service is either ready to receive the benchmark workload or it is not. We do not start measurement while the process is still somewhere between launch and a stable request path.
The warmup window matters for both sides of this comparison. On the JVM, interpretation, profiling, and compilation can change early behavior materially, which is why warmup is a first-class benchmark concern. On Go, allocator behavior, page faults, connection reuse, cache warming, and general runtime settling can also change the shape of the first part of a run. Warmup is not “for Java.” It is for any runtime where early execution is not yet representative of steady state.
The measurement window is the only phase that contributes to later throughput and latency aggregates. We may collect telemetry across more of the run, but we do not let startup and warmup leak into the numbers we later describe as steady state.
The post-run capture phase matters just as much as the measured window. A run that cannot explain itself is not worth much. We need the latency artifact, runtime signals, process output, and acceptance decision while the context is still intact.
One measured run includes setup and observability work around the measured window, but only the steady-state segment belongs in later performance aggregates.
A strict phase model gives us two things. It makes later analysis reviewable, and it gives us a clear basis for rejecting runs when the boundaries break.
How CPU limits and host frequency controls are handled
Single-machine benchmarks get fragile quickly when CPU shape is described loosely.
Saying “this ran with 2 CPUs” is not enough. Two CPUs enforced through a cpuset, two CPUs implied by quota, two CPUs inferred by a runtime override, and two CPUs on a noisy unrestricted host are not the same condition. They affect scheduling, thread placement, contention, and runtime heuristics differently.
That is why we record the OS-visible CPU allocation method as part of the benchmark cell rather than treating CPU count as self-explanatory. Runtime-level alignment still matters, but it does not replace host-level CPU shaping.
Host-visible CPU limits and runtime-level processor settings both matter. In modern Go and Java toolchains, effective parallelism can be influenced by the CPUs and limits visible to the process, so later articles will capture both the host mechanism and any explicit runtime overrides. On the Java side, -XX:ActiveProcessorCount gives us an explicit processor-count override when we need it. Those features are useful, but they also make it more important to record what the host actually exposed to the process.
Our rule for this series is straightforward: CPU-limited comparisons use the same host-visible allocation method across variants whenever practical. If we align a runtime with an explicit flag, that alignment belongs in the manifest, but the primary description of the benchmark cell is still the host-level mechanism.
For every measured benchmark cell, the record captures the CPU allocation mechanism, the effective CPU allocation value, governor state, turbo or boost status, whether the service and load generator share cores, and whether the runtime was additionally aligned with explicit runtime settings.
CPU counts are only comparable when we also record the control mechanism, governor state, turbo status, and where the service and load generator were placed.
Frequency behavior matters too. Even when the software stack does not change, governor mode or turbo behavior can shift the run shape. Linux CPU frequency behavior is exposed through cpufreq and platform-specific drivers such as intel_pstate, which is why we treat governor state and boost visibility as required host facts rather than optional color. We prefer performance governor mode during measurement and we document whether turbo or boost is enabled. If the host does not let us control those settings directly, that limitation belongs in the manifest and in the interpretation.
The placement of the load generator matters just as much. If the service and load generator fight for the same cores, then the result is telling us about a contested host layout, not just the service under test. We want placement assumptions to be explicit rather than silently baked into the numbers.
How repeats, run ordering, and drift are managed
A benchmark gets a false sense of certainty very quickly if you run one variant first, another later, and report whichever run shape looks neatest.
We are doing the opposite.
Every important benchmark cell gets repeated measured runs, and those runs are scheduled to reduce drift bias. That means we do not run all Go first and all Java later. We do not cluster one runtime shape in the cool part of the day and another after the machine has already been busy for hours. Time drift, thermal drift, and background variance are real enough to matter on a single host.
The policy is fixed even before the execution package appears. Every primary comparison cell needs at least three accepted measured runs before it can appear in an aggregate chart. Warmup and cooldown happen per measured run. Run order is rotated or randomized within a balanced schedule. Excluded runs remain visible with their exclusion reasons. If a cell cannot produce three accepted runs without intervention, it is treated as unstable and flagged for diagnosis rather than summarized as if it were settled.
That last point matters. We are not collecting a pile of numbers and then selecting the subset that makes the chart look cleaner. We are defining comparable conditions in advance and keeping the decisions visible.
Balanced ordering becomes even more important when two runtime shapes are close. If the observed difference is modest, protocol quality matters more, not less. A loose schedule can create a story that the runtime never earned.
We also need enough repeats to say something about stability. A single strong run is not a result. At most, it is a clue.
What makes a run invalid
This is where benchmark writing often gets evasive. You see a sentence like “we removed a few noisy runs,” and suddenly you do not know whether the team corrected a harness mistake or quietly curated the result set.
We want the acceptance rules to be simple enough to audit.
A measured run is accepted only if all of these conditions hold:
the preflight snapshot completed and matches the declared benchmark cell
the service reached readiness and held it before warmup began
the measured window started only after the declared warmup phase ended
response-validity checks passed and measured-window error rates stayed within the declared acceptance rule for that workload
the mandatory telemetry and artifact set was captured successfully
required host controls did not drift during the run
the load generator stayed within its validated headroom envelope and did not saturate before the service
post-run verification did not reveal a mismatch between the run and the declared cell definition
In plain language, the policy is this:
If preflight failed, do not measure.
If readiness failed, discard the run and fix service state.
If the measured window began before warmup completed, invalidate the run.
If mandatory artifacts are missing, invalidate the run.
If host control state changed during the run, invalidate the run.
If the load generator saturated first, do not treat the result as service capacity.
If correctness checks failed, do not accept the run as a performance result.
If the run is unusual but artifacts are intact, keep it visible and flag it for investigation rather than silently averaging it in.
The important part here is not the wording. It is that the reasons to reject a run are operational and visible rather than aesthetic.
A few definitions make the contract clearer.
Warmup bleed-through means either the harness started the measured window before the declared warmup duration elapsed, or the phase markers show readiness or startup-state transitions still crossing into the measured segment.
Host drift means that a required control changed between preflight and post-run verification, such as CPU allocation, governor mode, turbo or boost visibility, memory limit, or the intended service-versus-load-generator placement.
Load-generator limit means the client side saturated first and could no longer sustain the target workload shape. For the primary load profile in this series, that headroom rule is validated separately: client CPU must stay below the established ceiling for the load profile, and a control test against a known-fast endpoint must show throughput headroom above the service under test. If that evidence is missing, the run does not qualify as a capacity result.
Run outcomes map to explicit actions: discard before measurement, invalidate and rerun after contract failures, flag intact but unusual runs, or accept runs that pass every gate.
It also helps to separate a few different outcomes.
A discard usually means the run should not have proceeded under those conditions at all, such as failed readiness or failed preflight.
An invalidate means the run happened, but the measurement window is not comparable because part of the contract failed.
A rerun after stabilization means the issue may be transient but explainable, such as host drift or obvious startup bleed-through.
A flag for investigation means the artifacts are intact, but the run deserves diagnosis before it is allowed into any aggregate.
That distinction matters because a trustworthy benchmark does not make questionable runs disappear. It keeps them visible in raw records and excludes them for named reasons.
What telemetry we capture for every accepted run
A benchmark that reports only throughput and a couple of latency percentiles is easy to publish and hard to interpret.
For this series, every accepted run needs enough evidence to support or challenge the explanation that follows. That does not mean turning on every profiler for every measurement run. Telemetry can perturb the benchmark, so the profile has to be standardized. It does mean that each accepted run needs a minimum artifact package, and suspicious runs need a clear path to deeper diagnostic reruns.
Each accepted run must persist enough data to answer these questions:
What throughput did the service deliver, and with what error rate?
What did the latency distribution look like across the measured window?
Did the service keep returning valid responses for the declared workload?
How much CPU and memory did the service consume under the declared telemetry profile?
What runtime-specific memory, allocation, and GC signals are needed to explain anomalies?
Was the load generator still inside its validated headroom envelope?
Does the artifact set prove that the run matched the declared benchmark cell?
Latency distributions matter because load-generation method can distort tail-latency interpretation. That is one reason we preserve full latency artifacts rather than only a summary number. Later articles will identify the workload model and latency artifact format explicitly rather than relying on summary percentiles alone.
On the Java side, that means enough standardized runtime visibility to explain GC and runtime behavior without guessing after the fact. The exact capture mechanism belongs in the execution package, but the methodology requirement is stable: baseline measured runs use a declared low-overhead telemetry profile, and deeper runtime captures belong to explicitly labeled diagnostic reruns.
On the Go side, the rule is the same even if the tools differ. We need enough runtime visibility to explain allocation behavior, heap movement, or scheduler shape without turning every measured run into an intrusive profiling session. That telemetry profile is part of the benchmark cell definition, so readers can see what was always on and what was diagnostic-only.
A representative accepted-run package looks like this.
Required common artifacts
cell.yaml
preflight.txt
launch-summary.txt
service.stdout
service.stderr
env-summary.txt
load-summary.txt
latency-artifact
resource-sample-artifact
acceptance-decision.txt
Required runtime-specific artifacts for the declared telemetry profile
runtime version capture
runtime logs required by the declared profile
runtime memory or GC evidence required by the declared profile
Diagnostic-only artifacts for labeled reruns
deeper runtime captures produced only when the rerun policy calls for them
Not every runtime-specific file exists for every benchmark cell, and that is fine. What matters is that the telemetry profile is declared and the expected artifacts for that profile are actually present.
This series requires an artifact manifest and minimum evidence package for every accepted run. The next article will publish the concrete layout and capture details used to satisfy that requirement.
How this constrains later analysis
This is not the statistics article. That comes next. But the protocol only works if the interpretation posture is visible now.
The posture is deliberately conservative.
We are not going to make ranking claims from one good repeat. We are not going to treat throughput-only charts as complete. We are not going to hide discarded runs. We are not going to treat small differences as meaningful when the measurement uncertainty is of similar size.
That means later aggregation has to preserve enough information for review: repeat counts, central tendency, spread, and benchmark-cell inclusion decisions. A clean-looking median from a mixed bag of accepted and questionable runs is not good enough. A peak-throughput chart without the variance story is not enough. A p99 chart without CPU or runtime context is not enough either.
The practical reason is simple. Throughput, latency, CPU, RSS, heap, allocation, and runtime signals describe the same run from different angles. If one moves and the others do not, that tells us something. If they all move together, that tells us something else. Reading them together is how we avoid shallow explanations like “runtime A is faster” when the real story is “runtime A used more CPU to get there” or “runtime B’s tail changed because the host drifted and that run should not have been accepted.”
So the protocol imposes three rules on later articles. First, later charts aggregate accepted runs only. Second, later claims stay scoped to the measured runtime shape and benchmark cell. We do not stretch a narrow benchmark into a broad language verdict. Third, when spread is large or the observed effect is small, the article language stays correspondingly modest.
That is not timid writing. It is what defensible benchmark writing sounds like.
What artifacts must be saved for reproduction
A reproducible benchmark needs more than a general setup description. It needs a handoff package another engineer could use to rerun the work.
This article defines the contract. The next article will publish the executable side of that contract: exact environment disclosure, exact commands, manifests, run ordering, packaging details, and rerun instructions. After that, the analysis article will define how accepted artifacts become charts, including the canonical data shape, aggregation rules, uncertainty treatment, and charting constraints.
That separation is deliberate. It keeps this article focused on the measurement contract instead of turning it into a shell-script dump, and it keeps later claims tied to a visible analysis method.
For this series, reproducibility does not mean “an experienced engineer could probably guess the missing steps.” It means every accepted run leaves behind enough durable evidence that another engineer can inspect the benchmark cell definition, host controls, launch conditions, telemetry profile, measured outputs, and acceptance decision.
That is why the artifact manifest matters as much as the chart.
It is also why runtime identity belongs in manifests instead of fuzzy labels. Later articles will keep JDK distribution identity explicit, because support model, packaging, and build provenance can matter operationally even when distributions derive from the same OpenJDK codebase. If later articles add more than one Helidon SE execution mode, each one has to be named in the benchmark cell and preserved in the artifacts. If we compare multiple JDK distributions, that identity has to stay explicit. If later articles add a non-baseline Java execution mode, its setup assumptions and reproducibility requirements must be documented as part of that runtime variant rather than folded into a generic “Java” label.
If the series later includes GraalVM Native Image, it will be reported as a separate execution mode, not grouped with HotSpot-based Java runs. If later articles include startup-optimized or ahead-of-time Java modes, they will name the exact released technology used rather than using “Project Leyden” as a catch-all label.
What this article does not claim
This methodology is narrower than “how to benchmark web services” in general, and that is intentional.
It is designed for this series: a single-machine Linux/Bash benchmark comparing specific Go and Helidon SE service shapes under controlled CPU, concurrency, and payload conditions. It is not a Kubernetes benchmark, a cluster benchmark, or a production cost model. It does not stand in for every Java framework or every Go server architecture.
It also does not claim that these controls eliminate bias or guarantee a universal winner. What they do is reduce noise, lower the chance of false confidence, and make later numbers easier to challenge and reproduce.
That narrowness is a strength. It lets us be explicit about the protocol without pretending the result answers questions it was never designed to answer.
What comes next
The next step is not a winner chart. The next step is the executable benchmark package.
In the next article, we will publish the exact environment details, manifests, version capture, run order, and rerun instructions that implement this methodology on a real host. That is where you will be able to inspect the concrete CPU-limiting mechanism, runtime identities, telemetry-profile choices, workload model, and artifact layout used for the benchmark runs.
After that, we will publish the analysis rules that govern how accepted runs become charts and how uncertainty is reported. That is where the statistical and visualization constraints become just as inspectable as the run protocol.
If this article did its job, you now know what later results are obligated to prove, what evidence they must carry, and what kinds of numbers we will reject instead of averaging away.
]]>https://redstack.dev/2026/10/26/the-benchmark-methodology-behind-this-series/feed/04866Choosing and Proving the Load Generator
https://redstack.dev/2026/10/22/choosing-and-proving-the-load-generator/
https://redstack.dev/2026/10/22/choosing-and-proving-the-load-generator/#respondThu, 22 Oct 2026 16:01:00 +0000https://redstack.dev/?p=4858Continue reading →]]>Key Takeaways
The load generator is part of the benchmark instrument, not background plumbing. If the client saturates first or changes the arrival pattern under stress, later Go-versus-Java charts stop meaning what they appear to mean.
For this series, the primary generator is benchctl, the compact Go load driver in the benchmark package. We selected it because it can hold an explicit rate, retain per-request artifacts, and fit the series’ Linux-and-Bash workflow without hiding the method behind another framework.
Coordinated omission is not benchmark trivia. If the client naturally slows down during a stall, tail latency can look cleaner than the arriving workload actually experienced, so our main latency evidence uses fixed-rate pressure rather than purely response-paced discovery.
Headroom is a gate, not an assumption. The accepted validation evidence keeps the generator below the 80% CPU gate at selected target rates, proves margin with a known-fast control service, and keeps client-limited cells as failure evidence instead of quietly promoting them into the comparison.
If you want a skeptical reader to trust the later benchmark charts, you have to earn that trust before the first results article.
That starts with the client.
A load generator can flatten throughput for the wrong reason, hide a stall behind response-paced behavior, or become the busiest process on the machine before the service under test is actually in trouble. In a single-machine series, the risk is even sharper because client and service share the same CPUs, caches, memory bandwidth, scheduler behavior, and loopback path.
That is why this article exists between the implementation work and the full benchmark-method article. Before we talk about warmup, repeats, CPU shaping, or result analysis, we need to show that the driver itself deserves trust.
Figure 1. We validate the load generator as part of the measurement instrument: one host, one rate-controlled client, explicit CPU capture, and retained artifacts for both the control endpoint and the service under test.
Why the load generator gets its own article
Benchmark readers usually know the obvious failure mode: the client tops out before the server does.
The more dangerous failure mode is quieter. The client still looks plausible, the throughput line still climbs, and the latency summary still looks neat enough to publish. But once the service begins to stall, the client changes its own behavior and stops applying the pressure you thought you were measuring.
That is how a benchmark can look disciplined while still telling the wrong story.
So we treat the load generator as part of the measurement apparatus, not as setup glue. If we would not trust a server-side result without knowing the runtime flags, CPU limits, and logging state, we should not trust a client-side result without knowing the pacing model, telemetry, and headroom either.
This article’s claim is narrow on purpose. We are not trying to prove a universal winner among HTTP load tools. We are trying to prove something more useful for this series: the chosen client is unlikely to be the dominant limiter at the rates we plan to measure, and the harness tells us when that stops being true.
What the generator has to do in this series
The generator has to support the benchmark question, not just produce traffic.
For this series, that means it must drive requests at explicit target rates, preserve latency events that can be inspected later, record client-side errors, and fit into a repeatable Linux/Bash workflow. It also has to work with the same artifact discipline as the services under test: raw event streams, process samples, derived summaries, and clear pass/fail decisions.
That combination matters because the later articles compare Go net/http, Java Helidon on an Oracle-built JDK, and the Oracle JDK AOT/cache path under controlled single-machine conditions. The load tool cannot be a black box in that comparison. It must expose enough evidence for a reader to ask, “Was the client the limiter?” and get a concrete answer.
What we selected and why
For this series, the primary generator is benchctl, the compact Go load driver that ships with the benchmark package.
That choice is about fit, not prestige.
We needed a generator that could do three things well. First, it had to support explicit target rates, because the series is asking not only how fast a service can run in a closed loop, but also what happens when requests keep arriving at a planned rate. Second, it had to retain inspectable per-request artifacts rather than just printing a final aggregate line and disappearing. Third, it had to fit a Bash-first workflow cleanly so the benchmark remained easy to audit.
benchctl met those requirements directly. It supports closed-loop discovery when we want a rough ceiling, fixed-rate runs when we want evidence-bearing latency rows, and raw JSONL artifacts that preserve each measured request. That last point matters. Later analysis can inspect what the client actually did instead of trusting a single terminal summary.
Just as important, benchctl is part of the same source package as the services and the control endpoint. That makes it easier to tie request artifacts, process sampling, target-rate selection, and headroom checks into one reproducible flow.
We still keep the claim bounded. Choosing a tool does not prove the benchmark is fair. It only tells you which instrument we are putting under scrutiny.
Figure 2. We selected the generator that best fits this series’ trust requirements: explicit rate control, inspectable latency output, Linux and Bash automation fit, and reproducible artifact capture.
Why coordinated omission matters here
A response-paced client answers one question. A fixed-rate client answers another.
With response-paced load, new requests are naturally coupled to earlier responses finishing. If the service stalls, the client slows down too. That makes the worst part of the stall look cleaner than it should because fewer new requests arrive while the system is already struggling.
That is coordinated omission in practical terms: the client quietly stops applying pressure at the exact moment when arriving work would still have been feeling delay.
This does not mean closed-loop discovery is useless. We still use it to find rough ceilings and to expose where a given client shape begins to saturate. But it is not our main latency evidence. For the benchmark question in this series, the important row is the one where requests continue arriving at the configured rate and the latency record shows what that pressure looked like.
So the policy is simple. Evidence-bearing latency rows use fixed-rate pressure. Closed-loop discovery remains useful, but if it saturates the client or answers a different pacing question, it does not become the row we cite as the main latency result.
That distinction is one of the reasons the retained raw event stream matters so much. It gives us enough detail to audit the run later instead of treating the client as a black box.
Figure 3. Response-paced load can appear cleaner than it should during a stall because the client naturally slows down. Our policy uses scheduled pressure so the latency record better reflects what arriving work experienced.
The validation rule: prove headroom before a run counts
The operational rule is intentionally strict.
In this series, the load generator has to stay below a sustained 80% CPU gate at the selected target rates, and a separate known-fast control service has to prove throughput margin above the service-under-test demand.
Those are two different checks, and we need both.
The CPU gate catches the obvious problem: the client itself is running out of room. The control-service gate catches a subtler one: a client can stay under its CPU threshold and still fail to provide enough throughput margin for the real benchmark.
The control service in this package is fast-echo, a deliberately boring HTTP target. It is not part of the Go-versus-Java comparison. Its job is narrower than that. It tells us whether the client can comfortably exceed the throughput band selected for the benchmark cells.
This is also where negative evidence becomes useful instead of embarrassing. If a discovery cell or a control attempt saturates the client, we keep it. It becomes proof that the gate is working, not something we quietly discard.
What the validation showed
The important point is that the current package contains validation evidence, not just a policy.
The accepted fixed-rate probes were used to choose the final controlled-load rates. The final rate-selection note accepted 200, 400, and 800 requests per second for the long benchmark. That decision was based on fixed-rate probes, not on a closed-loop capacity leaderboard.
The evidence is compact enough to show directly:
Lower fixed-rate probe
Scope: 100 and 200 req/s across the required Oracle-built-JDK comparison shape
Accepted evidence: 108 rows; 162,000 measured requests; all 2xx; zero errors; 108/108 saturation rows passed
Load-generator CPU result: Maximum reported load-generator CPU: 15.559802%
Why it matters: Supports 200 req/s as a clean selected rate
Higher fixed-rate probe
Scope: 400 and 800 req/s across the same required variants, fixtures, CPU shapes, and concurrency levels
Accepted evidence: 108 rows; 648,000 measured requests; all 2xx; zero errors; 108/108 saturation rows passed
Load-generator CPU result: Maximum reported load-generator CPU: 40.503938%
Why it matters: Supports 400 and 800 req/s as clean selected rates
Final controlled-load run
Scope: Selected 200, 400, and 800 req/s rates
Accepted evidence: 486 measured cells; 6,804,000 measured non-warmup requests; all 2xx; zero request errors
Load-generator CPU result: After excluding terminal shutdown sampler rows with zero CPU ticks and zero file descriptors, 486/486 cells passed; maximum adjusted load-generator CPU: 44.447241%; maximum adjusted average load-generator CPU: 23.722782%
Why it matters: Shows the final selected rates were driven below the load-generator CPU gate
fast-echo control
Scope: Known-fast local control endpoint
Accepted evidence: Best observed control throughput: 38,067.4 req/s at concurrency 64; zero request errors
Load-generator CPU result: Control run used for client headroom, not service ranking
Why it matters: Demonstrates client-side headroom above the selected 800 req/s ceiling
The final controlled-load run deserves one extra explanation. The canonical saturation check flagged 51 terminal process-sampler rows where CPU tick counters decreased as the load-generator process exited. The supplemental audit ignored only terminal shutdown rows with zero CPU ticks and zero file descriptors, then found all 486 measured cells passing the adjusted saturation check. That is a narrow correction for process shutdown sampling, not a broad waiver for inconvenient data.
The fast-echo control run gives the other half of the headroom story. In the Oracle-only headroom manifest, the known-fast control service reached 38,067.4 requests per second at concurrency 64, with zero request errors, in a short local headroom run. That is not a service-under-test benchmark result. It is instrument validation: evidence that the client and local path can exceed the selected final controlled-load rates by a wide margin.
That is what we want from a benchmark harness. Not “the client always wins,” but “the harness shows where a client shape stops being safe.”
Why the control endpoint matters more than a pretty throughput number
A control endpoint is easy to misunderstand.
Readers see an echo-style endpoint and assume the article is trying to sneak in a flattering benchmark number. That is not the point. The control target is not there to rank services. It is there to calibrate the measurement instrument.
To do that well, the endpoint has to be intentionally simple: stable body, stable status, no database call, no downstream RPC, no template rendering, no application-specific hot path. The more boring it is, the more useful it becomes for this job.
fast-echo did exactly what we needed. It showed that the client could exceed the selected benchmark demand in a passing shape, and it also exposed whether a client shape was not good enough. Both outcomes matter. A passing control proves headroom. A failing control proves the gate is real.
That is why the control-service evidence belongs here even though it is not a benchmark result in the usual sense.
What this still does not prove
This validation clears an important hurdle, but it does not answer every benchmark question.
It does not turn same-host measurement into a separate load-generator host. Client and service still share CPUs, caches, memory bandwidth, scheduler behavior, and loopback networking. Those interactions can still matter, especially in the tail.
It does not mean closed-loop discovery is bad or fixed-rate pressure is perfect. Those modes answer different questions, and we use them differently on purpose.
It does not prove that the later Go or Java implementation is faster. The claim here is narrower: the current load generator, saturation gate, and control proof are strong enough that the next article can talk about benchmark methodology without leaving the client as an unexamined weak spot.
That is the right level of confidence for this stage.
Acceptance criteria before any benchmark run counts
Before a later Go-versus-Java cell can count as benchmark evidence in this series, it has to clear the same contract:
Correct pacing mode: evidence-bearing latency rows use the series’ fixed-rate mode, not an accidental response-paced fallback.
Generator CPU below the gate: the load generator must stay below the sustained 80% CPU threshold for the target cell.
Control-service headroom: the known-fast control service must show throughput above the selected benchmark demand.
No hidden client failure: rows with client saturation, unstable scaling, missing telemetry, or client-side errors are kept as failure evidence, not promoted into comparison data.
Retained artifacts: raw request events, process samples, and derived summaries must be present so the run can be audited later.
Those rules are strict because they need to be. A series that plans to compare languages and runtime shapes needs hard acceptance criteria long before it needs opinions.
Figure 4. A benchmark run only counts after the instrument passes: right tool mode, valid control proof, acceptable CPU headroom, retained artifacts, and no client-side saturation.
What this unlocks next
With the load tool validated, the next article can focus on benchmark methodology instead of first arguing about whether the client was the real limiter.
That changes the conversation in a useful way. We can move on to warmup policy, measurement windows, repeat counts, CPU-shape rules, invalid-run handling, and reproducibility knowing that the client side already has a defined contract and bounded proof behind it.
There is still plenty left to scrutinize. There should be. But the next scrutiny can be about the method and the service behavior, not about an unproven driver hiding in the background.
Conclusion
The benchmark before the benchmark is the load generator.
For this series, we selected benchctl because it matches the method we actually need: explicit rate control, inspectable raw artifacts, and tight integration with the package’s validation flow. We then validated it the way a measurement instrument should be validated, not the way a convenience tool is usually waved through.
The important result is not that every client shape passed. It is that the harness selected final controlled-load rates only after clean fixed-rate probes, then carried the same headroom discipline into the final matrix. The final accepted rates are 200, 400, and 800 requests per second. The accepted probes reached those rates without request errors or load-generator saturation, the final controlled run stayed below the load-generator CPU gate after accounting for terminal sampler shutdown rows, and the fast-echo control showed substantial local client headroom above the selected ceiling.
That does not settle the Go-versus-Java question. It settles the more basic question first: whether later runs are being driven by a tool we have reason to trust.
]]>https://redstack.dev/2026/10/22/choosing-and-proving-the-load-generator/feed/04858The Go Implementation Contract Before Benchmark Results
https://redstack.dev/2026/10/20/the-go-implementation-contract-before-benchmark-results/
https://redstack.dev/2026/10/20/the-go-implementation-contract-before-benchmark-results/#respondTue, 20 Oct 2026 16:01:00 +0000https://redstack.dev/?p=4853Continue reading →]]>Key Takeaways
This fourth article in our ten-part single-machine Linux benchmark series defines the Go net/http contract before any Go-versus-Java results are published.
The Go service must match the Article 02 HTTP behavior at the external boundary: endpoints, JSON rules, validation, error envelopes, deterministic payload generation, and extraWork checksum semantics.
Go does not need to imitate the Helidon SE implementation from Article 03. It does need to prove that it performs the same declared work and reports enough runtime evidence to make later results auditable.
Runtime tuning is part of the benchmark input. Defaults come first; any GOMAXPROCS, GOMEMLIMIT, GOGC, diagnostics, profiling, CPU, or memory variation needs a clear run label and manifest evidence.
Before we believe a future Go-versus-Java chart, we need to know exactly what the Go service is doing.
Not “it is a small Go program.” Not “it uses the standard library.” Not “it looks equivalent.” We need to know where the request is decoded, how validation fails, whether unknown JSON fields are rejected, whether duplicate fields are caught, what extraWork contributes to the response, whether one side silently enables a timeout or protocol mode, and which runtime settings were active when the run was measured.
That is the job of this article.
This is a contract article, not a results article. It defines the Go net/http service shape and the runtime evidence required before any Go result can be compared with the Java/Helidon variants from Article 03. We are not producing Go benchmark numbers here. We are not generating the benchmark source package here. We are defining what must be true before Go net/http results can be compared defensibly with the Java side.
If you build Oracle AI Database-backed services, this matters even before a database call enters the benchmark. A retrieval API, embedding gateway, reranking service, feature-enrichment layer, or vector-search facade often spends real CPU and memory in ordinary application-tier work: HTTP handling, JSON decoding, validation, enrichment, response shaping, logging boundaries, and runtime scheduling.
This article does not measure Oracle AI Database. It defines the Go service boundary so later database-backed workloads do not blur service-tier behavior with database behavior.
Short Answer: The Go Contract
The Go benchmark side must be a declared net/http service that implements the Article 2 HTTP contract and aligns with the Java/Helidon plan from Article 3 at the external behavior level.
The final Go service exposes the same GET /health, HEAD /health, and POST /work behavior; applies the same JSON media-type policy, request body limit, validation rules, duplicate-field and unknown-field rejection, deterministic payload generation, extraWork checksum semantics, success response, and JSON error envelope; and keeps primary-run logging, TLS, compression, and tracing off unless a later labeled slice enables them symmetrically.
The Go implementation does not need to imitate Helidon internals. It does need to prove that it is doing the same declared work. extraWork is a first-class equivalence gate because it affects the returned checksum and must not be skipped, reduced, duplicated, reordered, or optimized away.
The runtime side needs the same discipline. Defaults come first. Tuned runs are allowed only under clear labels, with GOMAXPROCS, CPU context, memory limits, GOMEMLIMIT, GOGC, server settings, allocation evidence, GC evidence, runtime/metrics snapshots, and pprof artifacts tied to the benchmark manifest.
Exact Go, Java, OS, kernel, CPU, memory, and tool versions will be recorded in the benchmark manifest when accepted runs are executed.
What Articles 1 to 3 Established
Article 1 set the series rule: method first, measurement later. We are not trying to make a language-war claim. We are building an evidence chain strong enough that later results can be challenged on method, source, runtime identity, load-generator validity, execution protocol, and analysis rules.
Article 2 defined the language-neutral service behavior that both implementations must follow. For the Go implementation, that means using the Article 2 endpoint list, request schema, response schema, body-limit policy, JSON media-type rules, validation rules, error envelope, deterministic payload-generation rules, and extraWork semantics without alteration.
The relevant service shape is intentionally small. GET /health returns stable JSON:
{
"status":"ok"
}
POST /work accepts a JSON object containing requestId, payloadSize, seed, and extraWork, subject to the Article 2 media-type, body-size, field, and numeric-validation rules. The service enforces the /work request-body limit, rejects unknown fields, rejects duplicate top-level fields, validates integer bounds and types strictly, generates deterministic payload bytes from payloadSize and seed, applies deterministic repeated SHA-256 work controlled by extraWork, and returns a stable success response containing requestId, payloadSize, extraWork, checksum, and ok.
Failures that use response bodies return the agreed JSON error envelope. Framework-default HTML pages, stack traces, plain-text errors, extra runtime metadata, and implementation-specific error documents are contract failures.
Article 03 defined the Java-side implementation plan and the evidence that the Java run must provide. This article uses that plan as the continuity point for external behavior and runtime evidence; it does not require Go to mirror Java internals.
The Java-side manifest must identify the exact JDK distribution, vendor, build, version, JVM mode, and relevant flags rather than treating Java, OpenJDK, and Oracle JDK as interchangeable runtime labels.
What This Article Covers
This article covers the Go net/http service shape, Article 2 equivalence, Article 3 alignment, extraWork review, runtime knobs, allocation and GC evidence, runtime/metrics, pprof, and acceptance gates.
It does not cover benchmark results. It does not define the load generator; Article 05 owns that. It does not define the full run protocol, CPU governor handling, warmup windows, repeat rules, invalid-run policy, or statistical analysis; those belong in later methodology and analysis articles.
It also does not move the series into Kubernetes or production orchestration. This ten-part series is scoped first to a controlled single-machine Linux benchmark. Host OS, kernel, CPU topology, CPU affinity or cgroup quota, memory limits, and runtime versions must be recorded in the manifest. The primary pure-service benchmark does not introduce Oracle AI Database driver behavior, SQL, vector-search execution, or database latency.
That boundary is deliberate. If implementation, tuning, load generation, execution, and analysis collapse into one step, the later chart becomes hard to trust. The Go side needs to pass its contract gates before source generation and benchmark execution.
We define the Go side as a contract gate: Article 2 supplies the external service behavior, Article 3 supplies the Java/Helidon alignment point, and Article 4 defines the Go gates that must pass before later source generation, benchmark execution, and analysis.
Why net/http Is the Go Baseline
The Go side uses the standard-library net/http package as the baseline. That is a good fit for this benchmark because it keeps the service path visible. Handler boundaries, request decoding, response writing, server settings, and diagnostics can be reviewed without also reviewing a third-party router, middleware framework, validation package, or alternate HTTP engine.
That is a reviewability argument, not a performance claim.
Go developers have good reasons to use frameworks and routers such as Gin, chi, Echo, Fiber, or fasthttp-based stacks in real services. Some provide better ergonomics for route grouping, middleware, validation, OpenAPI integration, structured errors, or specialized performance goals. Those choices can be useful production decisions. They are simply not the primary baseline for this series.
net/http is the right first baseline here because it is familiar, standard-library-based, and inspectable. The standard library keeps the baseline small, but it does not make the benchmark fair by itself. Fairness comes from matching the Article 2 contract, controlling runtime settings, capturing evidence, and rejecting runs that violate the rules.
The Go Service Shape
The Go service should be a single explicit net/http server shape for the primary pure-service benchmark. The exact source package comes later, but the implementation contract is already clear.
The route map comes from Article 2:
GET /health returns 200 OK and {"status":"ok"} as JSON.
HEAD /health follows HEAD behavior for the health resource.
POST /work is the measured work endpoint.
Unsupported methods and unknown routes follow the Article 02 status and JSON error rules. When Article 02 requires 405 Method Not Allowed, the response must include the contract-defined Allow header.
For HEAD /health, the Go handler must return the same headers and status policy defined for the health resource while writing no response body.
The handler path for POST /work is fixed at the contract level. The service checks the route and method, validates the media type, enforces the /work request body limit, decodes JSON, rejects duplicate and unknown top-level fields, validates required fields and scalar bounds, generates the deterministic payload, applies extraWork, computes the checksum, and returns the success JSON. Failures map to the Article 2 error envelope.
Here is the shape we want the final source to preserve. This is an illustrative contract snippet, not the generated benchmark source package:
// Illustrative contract shape only.
// The benchmark source package will be generated later from the finalized contracts.
funcmain(){
server:=&http.Server{
Addr:":8080",
Handler:http.HandlerFunc(route),
// Addr, timeouts, header limits, body limits, TLS, and protocol settings
// are illustrative here. Final values must be declared in the benchmark manifest.
The final source should set response Content-Type exactly as Article 2 specifies. The illustrative snippet uses application/json only to show that Go must not fall back to framework or net/http default error documents.
The final source may use ServeMux or another standard-library routing shape, but it cannot let default net/http error documents define the benchmark behavior. Unknown routes, unsupported methods, oversized bodies, malformed JSON, and validation failures must all map to the Article 02 status and JSON error contract. If the final source uses ServeMux method/path patterns rather than explicit method checks inside handlers, the selected Go toolchain’s ServeMux matching semantics must be recorded because those semantics are version-sensitive.
JSON handling will likely use encoding/json, because it is the standard-library JSON package and keeps dependencies low. But encoding/json defaults are not the contract. The implementation must not rely on convenient decoder behavior to define benchmark behavior.
Plain struct unmarshalling does not prove duplicate-field rejection, and unknown fields are ignored unless the decoder is configured or the implementation checks them explicitly. Article 02 rejects unknown fields and duplicate top-level request fields, so the Go source needs a token-level pass, json.RawMessage inspection, or another explicit mechanism that records top-level field names before decoding into the typed request model.
The same applies to numeric handling. Article 2 requires integer JSON numbers with no fractional part and no exponent notation for payloadSize, seed, and extraWork. Numeric validation should be explicit for the chosen decode path so strings, fractional forms, exponent notation, missing values, and out-of-range values are rejected exactly as Article 02 requires.
Server configuration also belongs in the contract. If the Go service uses http.Server timeouts, header limits, handler-level body limits such as http.MaxBytesReader, TLS, HTTP/2 settings, compression, or diagnostics listeners, those settings must be declared. The primary pure-service benchmark keeps request logging, TLS, compression, and tracing off unless a later secondary slice enables them symmetrically.
Logging has the same boundary. Build and startup logs are useful. Error diagnostics are useful. Per-request access logging is off for the primary measured path unless a later logging slice includes it deliberately. A hidden log line on every request can become part of the workload.
How the Go Contract Pairs With the Java Contract
Go does not need to imitate Helidon SE internals. Java does not need to imitate Go internals.
That sounds obvious, but it is a common benchmark trap. If we try to make Go look like Java inside the process, or Java look like Go, we stop comparing real service shapes and start building an artificial hybrid.
The Java implementation uses the Helidon SE configuration defined in Article 03. The Go implementation uses net/http. They are compared at the external contract level, not by assuming identical routing, scheduling, or runtime internals. Any Helidon/JDK threading mode, including virtual-thread-related settings if used, must be recorded in the Java run manifest.
Both implementations must satisfy the same HTTP behavior from Article 02. Both must implement the same deterministic payload generation and extraWork checksum behavior. Both must use the same primary-run posture for logging, TLS, compression, and tracing. Both must report enough runtime identity and diagnostic evidence to make later results auditable.
Article 3 defines the Java/Helidon side with its request-handling plan, runtime policy, and diagnostic evidence. This article defines the Go side with net/http, Go runtime settings, allocation and GC observability, and pprof artifacts.
They align at the contract level, not by sharing internals.
The extraWork Equivalence Review
extraWork is the part of this benchmark that most deserves suspicion.
In Article 2, extraWork is not a sleep, a delay knob, or a decorative loop. The service generates deterministic payload bytes from payloadSize and seed, computes an initial SHA-256 state, then applies a deterministic repeated operation extraWork times:
buffer = generatePayload(payloadSize, seed)
state = SHA-256(buffer)
repeat extraWork times:
state = SHA-256(state || buffer)
checksum = lowercaseHex(state)
Because the final checksum is returned, extraWork has an observable effect for the benchmark’s conformance test vectors. If the loop is skipped, shortened, duplicated, reordered, or changed, the expected checksum for those vectors will not match.
The Go implementation must treat this as declared per-request work. It is not a hidden trick and not a place for clever local interpretation. The comparison does not require Java and Go to execute identical machine instructions. It does require both services to perform the same externally specified operation for the same accepted request.
The equivalence assertion should be this direct:
given payload P
and configured extraWork=N
when the Go service handles P
and the Java service handles an equivalent P
then both services:
- validate P before performing accepted work
- generate the same deterministic payload bytes
- execute the declared work factor N
- produce the same checksum
- reject the same invalid values
- record extraWork=N in the benchmark manifest
The ordering matters. Invalid requests should fail validation before accepted work is performed. extraWork = 0 is valid and means no repeated extra operation after the initial payload checksum. extraWork above the Article 2 maximum is invalid. A string, fractional value, exponent notation, missing value, or negative value is invalid.
A few mistakes would invalidate the comparison immediately:
The comparison is invalid if:
- Go skips extraWork for a valid request that Java processes.
- Go performs fewer iterations because of integer truncation or a loop-bound mistake.
- Go allocates large temporary buffers inside the loop when the contract does not require them.
- Java performs extra hidden request work that is not declared in the Java contract.
- One implementation accepts extraWork=0 and the other rejects it.
- The work is optimized away because it has no observable or retained effect.
The allocation example needs careful handling. Different runtimes have different allocation behavior, and the benchmark does not require identical allocator internals. But if the Go source creates avoidable temporary structures inside the extraWork loop while the Java source reuses state for the same logical operation, that may be a benchmark implementation bug rather than a runtime finding.
The fix is not to tune around it after seeing results. The fix is to inspect the implementation, decide what the contract requires, test it, and only then allow the source into the benchmark package.
Before results are published, the benchmark source or contract appendix must include canonical checksum test vectors for accepted combinations of payloadSize, seed, and extraWork. extraWork is admissible only when both implementations do the same declared work for the same accepted request and fail the same invalid requests in the same way.
Runtime Tuning Is a Controlled Hypothesis
The Go runtime settings are not incidental. They shape how the process uses CPU and memory, how garbage collection is paced, and how later profiles should be interpreted.
The default run comes first. That default run should use the selected Go toolchain’s runtime defaults under the declared Linux machine or container environment. Tuned variations can come later, but only under labels that explain the hypothesis.
For example, future run labels might distinguish:
go-nethttp-default
go-nethttp-gomaxprocs-2
go-nethttp-gomemlimit-labeled
go-nethttp-gogc-labeled
go-nethttp-profiled
Those names are examples, not final manifest labels. The rule is the point: a tuned Go run without a manifest label is not reproducible enough to compare.
A compact future-run manifest excerpt shows the level of evidence required:
This manifest is not evidence that a benchmark has run. It is the contract for what later accepted Go runs must record.
Because Go runtime defaults can change across Go releases and execution environments, the manifest should record both configured environment values and effective values observed by the benchmark process. Shell environment alone is not enough. Accepted runs must capture the selected Go toolchain and the effective runtime values from inside the benchmark process or from a dedicated manifest probe built with the selected Go toolchain.
CPU and Memory Controls
GOMAXPROCS controls how many operating-system threads can execute Go code simultaneously. That setting matters because a service running with one effective CPU is not the same experiment as a service running with four, eight, or sixteen. It also matters when the process runs under CPU affinity, cgroup quota, or a container CPU limit.
The Go contract should record the observed GOMAXPROCS value, host CPU model, logical CPU count, CPU affinity if constrained, container CPU quota or limit if used, whether GOMAXPROCS was set manually, and the Go toolchain version that determined default behavior.
We should avoid advice like “set GOMAXPROCS to the number of cores.” That might be right in one environment and wrong in another. The benchmark question is simpler: what CPU budget did the process actually observe, what value did the runtime use, and was that value a default or a deliberate tuned variation?
Memory needs the same discipline. A container memory limit, host memory availability, process RSS, Go heap behavior, and Go runtime memory policy are related but not identical.
GOMEMLIMIT is a soft limit for memory managed by the Go runtime and garbage collector. It is not a hard cap on process RSS. If the benchmark uses GOMEMLIMIT, that setting must be recorded and labeled. If it is unset, that fact should also be recorded. The surrounding memory context still matters because a process can be constrained by an external memory limit even when the Go runtime setting is unset.
GOGC changes the garbage collector’s target percentage and represents a CPU/memory tradeoff. Changing it can reduce memory growth at the cost of more GC work, or reduce GC frequency at the cost of more memory, depending on direction and workload. This article does not recommend a universal GOGC value. The baseline uses defaults first; changing GOGC is a labeled hypothesis.
Allocation and GC Evidence
The Go implementation should avoid accidental allocations that are not required by the workload. That is not the same as over-optimizing Go.
For example, repeatedly rebuilding constant response metadata, copying request bodies unnecessarily, allocating a fresh large buffer inside every extraWork iteration, or formatting unused strings on the hot path can turn the benchmark into a measurement of source mistakes. Those are worth fixing before execution if they violate the contract or create avoidable asymmetry.
On the other hand, the Go side should not introduce exotic pooling, unsafe tricks, custom JSON encoders, or specialized buffer reuse unless those choices are declared and accepted as part of the benchmark. If we aggressively tune Go allocation behavior while leaving the Java side at a straightforward implementation, the comparison shifts from service-shape benchmarking into asymmetric hand-optimization.
The practical sequence is straightforward: implement the Article 02 contract plainly, measure allocation rate and GC behavior under representative conformance or diagnostic load, inspect whether allocation differences are contract-required, runtime-inherent, or source-level mistakes, fix source-level mistakes before benchmark execution, and label any deliberate optimization that changes the baseline service shape.
The later Go run artifacts should include allocation and heap evidence. That does not mean every primary measured run has to run with heavy profiling turned on. It means the benchmark plan must capture enough allocation and GC information to explain later throughput, latency, CPU, and memory shapes.
Allocation reductions are hypotheses. Profiles and metrics tell us whether the hypothesis is true.
runtime/metrics snapshots should be captured using the supported metric list for the selected Go version. The exact metric names belong in the later source package and manifest because the supported set can evolve. At minimum, the run should capture enough runtime data to reason about goroutines, scheduler behavior, memory, heap allocation, GC settings, GC pauses or timing summaries, and observed runtime configuration. The manifest should store both the collected metric values and the supported metric-name list reported by the selected Go version, so later analysis can distinguish “metric was zero” from “metric did not exist in this toolchain.”
pprof artifacts should be planned for profiled runs. CPU, heap, allocation, and goroutine profiles are the obvious starting point. Block or mutex profiles can be useful if the workload suggests contention, but they require explicit sampling configuration and should not be casually enabled in the primary path.
pprof is evidence capture, not free instrumentation. Profiled runs need labels, and interpretation belongs later, after accepted runs exist. If profiling changes the measurement environment, the profiled run should be separate from the primary comparison run.
A future diagnostics listener might be isolated from the measured service path. This snippet shows the idea without defining final source:
// Illustrative only.
// The final benchmark package must decide whether pprof is enabled,
// how it is isolated, and how profiled runs are labeled.
The important boundary is not port 6060; that is only a familiar local example. The important boundary is that diagnostics are declared, isolated where appropriate, and tied to the run label. The final source should define diagnostics-listener startup, failure, and shutdown behavior explicitly; the snippet above is not a production-ready or benchmark-ready lifecycle policy.
For each accepted Go run, the artifact plan should include the benchmark manifest, service configuration, runtime/metrics snapshot, allocation profile when profiling is enabled, heap profile when profiling is enabled, CPU profile when profiling is enabled, goroutine profile when profiling is enabled, and GC summary or trace setting if enabled.
Those artifacts do not replace results. They make later results diagnosable.
We plan Go runtime evidence before results exist: request handling, allocation behavior, scheduler and GC signals, runtime/metrics, and pprof artifacts all tie back to the benchmark manifest.
Acceptance Gates for the Go Implementation
The Go implementation is not accepted because it compiles. It is accepted only when it satisfies the contract gates.
Before the Go service is allowed into later benchmark source generation, Article 2 endpoint behavior must be implemented exactly. Routes must match the contract methods and paths. Request validation must reject unknown fields, duplicate top-level fields, wrong numeric types, out-of-range values, malformed JSON, unsupported media types, oversized bodies, unsupported methods, and unknown routes according to the agreed status and JSON error behavior. Success responses must match the Article 2 JSON contract.
The Go and Java implementations must also satisfy the same externally visible behavior. The Article 03 alignment gate keeps the Java side in view without forcing Go to mirror Helidon internals. If Java/Helidon adds a framework behavior that affects the contract, that behavior has to be declared and either matched externally or removed from the primary comparison.
The extraWork gate proves that Go and Java compute the same checksum for the same valid request and reject the same invalid work factors. It also forces us to inspect allocation behavior around the work loop before performance results are allowed.
The runtime manifest gate rejects unlabeled tuning. If GOMAXPROCS, GOMEMLIMIT, GOGC, CPU limits, memory limits, server timeouts, TLS, diagnostics mode, or profiling settings change, the run label and manifest must say so.
The allocation, GC, and pprof gates make sure future results can be explained. A surprising Go result without allocation, GC, runtime, or profile evidence is not a strong result. It is a guess with numbers attached.
And one gate is intentionally simple: no benchmark results are published from this article.
Why There Are No Results Yet
Charts would be premature here.
A Go throughput number published before the Go service contract is locked would not answer the series question. It would answer a less useful question: “What happened when this particular Go program, with these settings, was run under a not-yet-final method?”
That is not enough.
No Go result should be compared with Java until the implementation contract, source package, validation checks, load-generator evidence, run protocol, captured artifacts, and analysis rules all line up.
That order can feel slow if you want the chart. It is faster if you want a chart you can trust.
Conclusion: Handoff to Article 5
The Go side is now a contract, not a result claim.
We have defined why net/http is the baseline, how the Go service must implement the Article 2 endpoint behavior, how it aligns with the Java/Helidon plan from Article 3, why extraWork needs its own equivalence review, and which runtime settings and observability artifacts future Go runs must capture.
The next weak point is the client side. A service benchmark is not valid if the load generator is saturated, misconfigured, or measuring latency in a way that hides pauses. Article 05 moves to load-generator validity: request scheduling, coordinated-omission risk, client headroom, backpressure, timeout accounting, and the evidence needed to prove that later results are about the service under test rather than the benchmark harness.
]]>https://redstack.dev/2026/10/20/the-go-implementation-contract-before-benchmark-results/feed/04853Defining the Java/Helidon Benchmark Contract
https://redstack.dev/2026/10/16/defining-the-java-helidon-benchmark-contract/
https://redstack.dev/2026/10/16/defining-the-java-helidon-benchmark-contract/#respondFri, 16 Oct 2026 16:09:19 +0000https://redstack.dev/?p=4848Continue reading →]]>Key Takeaways
This article defines what Java means for this benchmark: a Helidon SE service running on explicitly identified Oracle-built JDK variants, with a declared request-handling model, JVM policy, diagnostics, and manifest evidence.
Virtual threads are treated as a request-handling model, not a performance claim. A later benchmark must prove which model was active and measure whether this workload benefits from it.
Runtime labels require exact build evidence. A later result is not accepted if it only says “Java” or “Java 21” without provider, version, build, architecture, flags, and environment details.
This article defines the Java contract only. The runnable benchmark package and benchmark results come later, after the series defines the full service contract, load generation, execution method, and analysis method.
You can make “Java” mean almost anything in a benchmark.
It might mean a plain JDK HTTP server, Spring Boot, Quarkus, Micronaut, Vert.x, Netty, or Helidon. It might mean platform threads, virtual threads, a reactive handler model, a native executable, a checkpoint/restore workflow, or an ordinary JVM run with JIT warmup.
It might mean default heap ergonomics, fixed heap settings, one garbage collector, another garbage collector, request logging on, TLS on, or a tuned command line nobody wrote down.
If a later chart labels one bar Java, that chart is already too vague.
This article defines the Java side before we measure it. For this benchmark, the Java service shape is Helidon SE. Measured Java evidence in this series is limited to explicitly identified Oracle-built JDK variants. The request-handling model must be declared. Startup and warmup boundaries must be separated. JVM tuning must be framed as a hypothesis. Diagnostics must be captured before results are accepted.
No benchmark result is published here. No winner is declared here. We are defining the Java/Helidon contract that later source code and benchmark runs must satisfy.
Where This Article Fits in the Series
This is Part 3 of a ten-part, single-machine benchmark series. Part 1 set the rule: method first, measurement later. A run is not useful because it completed; it is useful only if the service behavior, runtime identity, environment, load generator, run protocol, and analysis method are all traceable.
Part 2 defines the language-neutral service behavior. Both implementations expose the same health and work endpoints, follow the same request and response contract, and use the same posture for logging, TLS, compression, and related service settings in the primary pure-service benchmark.
Those requirements are not Java requirements or Go requirements. They are the HTTP contract both services must satisfy before either one is tuned or measured.
This article binds that neutral service contract to the Java implementation shape. It answers a practical question: when a later article says Java/Helidon, what exactly does that mean?
Part 4 applies the same discipline to the Go side. It defines the Go net/http implementation shape, runtime settings, profiling plan, and extraWork equivalence review. Parts 5 through 8 define load generation, execution, reproduction, and analysis. Results do not arrive until Part 9, with final interpretation in Part 10.
That ordering matters. If we tune Java first and define the Java contract afterward, the reader has to wonder whether the contract was shaped around the result. If we define the contract now, before source generation and before measurement, later Java results become auditable.
Later results must be generated fresh from the validated contract and preserved with the artifacts needed to audit them.
What “Java” Means in This Benchmark
For this benchmark, “Java” means a Helidon SE service that implements the finalized Article 02 endpoint contract exactly. The later implementation should make the Helidon SE WebServer routing and server configuration reviewable rather than relying on undocumented defaults.
That sentence intentionally excludes a lot. It does not say all Java services. It does not say all Java frameworks. It does not say Helidon represents Spring Boot, Quarkus, Micronaut, Vert.x, Netty, or a plain JDK server. Those are valid production choices, but they are outside the Java service shape selected for this benchmark.
Helidon SE is selected because its programmatic style can make routing and server configuration explicit in the benchmark source package. That helps reviewability for this particular contract. We want a reader to inspect the later source package and see the choices that matter, not infer them from a larger application stack.
The runnable benchmark must record the released Helidon SE version and resolved dependency set actually used for each run.
A later accepted Java run must identify the runtime shape in a manifest. This YAML is only an illustrative sketch, not the final manifest schema and not evidence that this article builds a service:
java_runtime:
implementation_id:"java-helidon-se"
framework:"Helidon SE"
manifest_must_record:
framework:
- helidon_version
- resolved_dependency_set
jdk:
- provider
- version_output_file
- runtime_properties_file
- system_settings_file
- effective_flags_file
- architecture
request_handling:
- selected_threading_model
- evidence_that_model_was_active
execution_policy:
- heap_policy
- gc_policy
- startup_boundary
- warmup_boundary
- measurement_boundary
diagnostics:
- gc_log
- jfr_recording_when_enabled
- process_metrics
- request_metrics
artifacts:
- raw_result_files
- summary_files
- manifest_links
The important point is not the field names. The important point is the chain of evidence. A later Java result must tie together the framework, dependency set, JDK build, request-handling model, JVM flags, heap and GC posture, diagnostics, warmup window, measurement window, and raw artifacts.
The Java side becomes auditable only when the framework, JDK identity, request-handling model, JVM policy, diagnostics, and manifest are treated as one contract.
Java Runtime-Shape Map
The Java benchmark result is not valid until the Helidon SE service shape, JDK variant, request-handling model, JVM flags, diagnostics, and manifest evidence are captured from the validated implementation.
Figure 1. We define the Java runtime shape before measurement: Article 2’s service contract flows into Helidon SE, an exact JDK variant, a declared request-handling model, JVM policy, diagnostics, and a manifest before results are allowed.
The diagram is a reminder that the benchmark does not start at the load generator. It starts with the service contract. The Java implementation must satisfy that contract, record its runtime identity, and capture enough diagnostics to explain later measurements.
The Java Service Contract
The Helidon SE service must implement the finalized Article 2 language-neutral contract without adding framework-specific drift.
That means the Java service must expose the Article 2 endpoints and behavior exactly, and the later Go service must be held to the same finalized contract. The Java service must use the same request body limit, accept the same JSON media types, reject the same invalid request shapes, enforce the same numeric bounds, reject unknown and duplicate top-level request fields, return the same success fields, and return the same JSON error shape for body-bearing failures.
The primary benchmark posture also stays the same: request logging off, TLS off, compression off, and tracing off unless a later secondary slice explicitly enables one of them for both implementations. A Helidon default cannot become a hidden benchmark input.
This is where framework details matter. JSON parsing can differ in duplicate-field handling, numeric coercion, unknown-field policy, and error reporting. If the selected JSON library does not reject duplicate top-level fields by default, the Java implementation must add an explicit parsing or validation step that does. Routing can differ in how unsupported methods are handled. Server defaults can affect request size limits, connection behavior, response headers, exception mapping, and log output.
None of those details necessarily makes one framework better or worse. Hidden differences simply make results harder to trust.
The later Java source package must make these choices explicit enough for conformance tests to fail when the service drifts. A framework-default HTML error page is not a small cosmetic issue in this benchmark; it is a contract failure. Accepting "payloadSize": "1024" as a string when the contract requires an integer JSON number is also a contract failure. Returning an extra diagnostic field in /health is a contract failure.
Benchmarks often rush toward tuning. Here, correctness and equivalence come first. A fast service that answers a different question is not evidence.
Runtime Variants and Manifest Policy
Runtime labels are not vague labels in this series. They are benchmark inputs that must be backed by exact evidence.
For the measured Java evidence in this comparison, accepted Java runtime variants must be built by Oracle and labeled precisely. Non-Oracle JDK distributions are outside this measured comparison unless a later article explicitly defines a new scope and records them as separate, verified evidence. A result is not accepted unless the run records the exact provider, version, build string, architecture, effective JVM flags, operating system, and available processors as seen by the JVM.
These command shapes show the kind of runtime evidence the benchmark package needs to preserve:
Those files preserve the basic runtime identity. artifacts/java-version.txt captures the version string, runtime build, and VM name. artifacts/java-runtime-properties.txt captures properties such as java.vendor, java.version, java.runtime.version, java.vm.name, os.name, and os.arch. artifacts/java-system-settings.txt captures system and container-related settings exposed by the selected JDK. artifacts/jvm-flags.txt captures effective JVM flags, including defaults and explicitly supplied options.
These commands do not prove benchmark correctness. They only show the kind of runtime evidence the later benchmark must preserve. -XshowSettings:system should be validated for each selected JDK and Linux environment because the exact system and container fields exposed by the launcher can vary.
If the benchmark runs inside a constrained environment, the manifest must also record CPU and memory limits visible to the JVM. JVM ergonomics use available processor and memory information. If the service sees two processors but the host has many more, that is not a footnote; it is part of the benchmark input.
The series will not infer a JDK advantage from branding. Runtime variants must run the same service contract, under the same run protocol, with comparable diagnostics, before any comparison is allowed. If a later result differs, the first question will be: what exact runtime, flags, machine state, and artifacts produced that difference?
Virtual Threads Are a Request-Handling Model, Not a Result Claim
Virtual threads matter for the Java side because they can change how the service handles concurrent requests. JEP 444 defines virtual threads as a final feature in JDK 21 and describes them as lightweight threads managed by the JDK rather than the operating system.
That does not make virtual threads a magic performance switch.
Virtual threads are especially relevant when a service uses a thread-per-task style and spends time blocked on I/O. They can make blocking-style code easier to write and scale for suitable workloads.
But they do not make CPU-bound work run faster. If the handler is mostly JSON parsing, deterministic payload generation, checksum work, allocation pressure, or CPU-bound simulation, virtual threads may not improve throughput. They may still affect scheduling behavior, memory pressure, thread diagnostics, and latency distribution.
The contract treats virtual threads as a declared request-handling model. A platform-thread versus virtual-thread comparison is allowed only if the selected Helidon SE release documents both modes in a way that keeps the framework version, endpoint code, server architecture, JVM flags, and other benchmark inputs constant. Otherwise, the benchmark should declare the supported Helidon request-handling model and omit the artificial comparison.
The important rule is isolation: if platform-thread and virtual-thread variants are compared, the benchmark must prove that only the intended request-handling variable changed.
Here is the contract idea as a small sketch, not a Helidon configuration file:
request_handling:
selected_model:"declared for the run"
comparison_model:"included only when supported and isolated"
Diagnostics matter here. Blocking behavior, synchronized regions, native calls, and pinned virtual threads can affect scalability. Pinning is not automatically a correctness bug, but it can explain why a virtual-thread service behaves differently from the mental model. Representative Java diagnostic runs should capture enough evidence to inspect thread behavior when the methodology calls for it.
So the benchmark will not say “virtual threads are faster.” It will ask a narrower question: under the Article 02 workload, with the selected Helidon SE service and selected JDK build, does this request-handling model change throughput, latency distribution, CPU use, memory use, warmup behavior, or diagnosability?
That question is measurable. The slogan is not.
Startup and Warmup Boundaries
The baseline Java execution model is an ordinary JVM run with a defined warmup boundary and a defined measurement boundary.
That sounds boring, and boring is good here. A JIT runtime needs warmup time. The service may initialize framework structures, compile hot paths, settle allocation behavior, and reach a different steady-state profile than it showed in the first few requests. Later methodology articles define the warmup interval, measurement interval, repeat count, invalid-run rules, and analysis rules.
Any Project Leyden-related startup or warmup path is handled separately and only if the selected JDK exposes a supported, reproducible workflow for the benchmark. Project Leyden focuses on startup time, time to peak performance, and footprint. If the selected JDK provides a supported Leyden-related workflow, such as ahead-of-time class loading and linking for that JDK, the benchmark may include it as a separately labeled startup and warmup variant with recorded commands, generated artifacts, checksums, and training input. If it does not, the variant is omitted.
The contract is simple:
startup_warmup_policy:
baseline:
mode:"ordinary-jvm"
included: true
warmup_boundary:"defined by later benchmark methodology"
leyden_related_variant:
included:"only when supported by the selected JDK"
required_evidence:
- jdk_version_and_build
- exact_record_create_run_commands
- generated_artifact_filenames
- generated_artifact_checksums
- training_input_description
- regeneration_rule_per_application_build
graalvm_native_image:
included_in_this_jvm_comparison: false
note:"Separate execution model; not silently mixed into JVM results."
This separation prevents a common confusion. Leyden-related HotSpot and JDK work is not the same thing as GraalVM Native Image. GraalVM Native Image compiles a Java application ahead of time into a native executable. That changes the build and runtime model. It may be worth measuring in a separate slice, but it is not silently part of the ordinary JVM comparison in this article.
Checkpoint and restore workflows belong in the same category: separate execution model unless explicitly defined. They should not slip into the primary Java/Helidon comparison just because they affect startup or warmup.
If a later article includes a supported Leyden-related path, the result must identify the generated artifacts, training traffic, checksums, commands, and regeneration rules. Startup features without artifact discipline quickly become unrepeatable anecdotes.
JVM Tuning Hypotheses
JVM tuning in this series starts as a hypothesis, not a conclusion.
A fixed heap may make memory behavior easier to compare, but it can increase GC frequency under some workloads. Ergonomic heap sizing may better reflect default production behavior, but it can make memory comparisons harder if the runtime adapts differently under constraints. A pause-time target can influence latency behavior, but it is a goal, not a hard guarantee. A different collector may help some workloads and hurt others. A setting that improves one percentile can move cost into CPU, allocation rate, RSS, warmup, or throughput.
So the primary Java baseline should be intentionally plain and reproducible before variants are added. A reasonable Java run profile might fix the selected JDK build, fix the selected Helidon SE version, declare heap policy, use a documented baseline collector such as G1 when selected, enable GC logging when methodology requires it, and capture enough runtime evidence to explain what happened.
This illustrative launch shape shows diagnostic intent. It is not a final benchmark runner, and target/java-service.jar is a placeholder for a later built service artifact rather than an artifact produced by this article:
If used later against a real service artifact, this style of run would produce a GC log and a Java Flight Recorder recording for diagnostic analysis. That does not make the command optimized. It only makes the run easier to inspect.
The later methodology decides which diagnostics are enabled during primary measurement and which are enabled only for representative diagnostic runs. Java Flight Recorder and profilers are useful, but they are not free. The benchmark has to define overhead policy rather than pretending diagnostics have no effect.
JVM tuning also needs to stay connected to the workload. An application service may spend time in HTTP handling, JSON serialization, validation, request shaping, vector-search calls, embedding calls, connection pools, or model gateways. The primary benchmark in this series isolates a pure service path first. If a later dependency slice adds a database call, the Java tuning question changes because blocking I/O, driver behavior, connection pooling, and database latency enter the picture.
That is another reason not to overfit JVM flags before the benchmark contract is complete.
Diagnostics Required Before Results
Diagnostics are not extra paperwork. They are how we avoid guessing.
If a later chart shows a latency spike, we need to know whether the service was CPU-saturated, allocating heavily, collecting frequently, warming up, blocked, pinned, hitting a request limit, logging unexpectedly, or being distorted by the load generator.
If a throughput difference appears between two runtime variants, we need to know whether the same flags, heap policy, and request-handling model were actually used. If memory differs, we need heap and RSS context, not a single number detached from GC behavior.
Every accepted Java run needs enough evidence to connect the observed HTTP behavior to the runtime state that produced it. That evidence includes runtime identity, framework identity, endpoint conformance, JVM behavior, process metrics, request metrics, and manifest links back to the raw artifacts.
Runtime identity means java -version, runtime properties, system settings, effective JVM flags, operating system, architecture, and available processors as seen by the JVM. Framework identity means the Helidon SE version, dependency set, and source revision used to build the service. Endpoint conformance means the Java service passed the Article 02 contract tests before measurement. JVM behavior means heap policy and GC evidence captured under the methodology’s diagnostics policy. Process and request metrics must cover the warmup and measurement windows, not just a single end-of-run snapshot.
Representative diagnostic runs can add more detail. Java Flight Recorder is especially useful on selected JDK builds where it is available and enabled for the benchmark methodology, because it can expose JVM events relevant to allocation, GC, I/O, threads, and runtime behavior. JDK Mission Control can later inspect Java Flight Recorder recordings when diagnostic analysis is needed.
async-profiler can add sampling views for CPU and allocation behavior, but it is a separate tool with platform and permission requirements. It should be used deliberately, not assumed to be present everywhere.
The goal is not to make every benchmark run heavy. The goal is to make every accepted result explainable. Primary measurement runs and representative diagnostic runs can have different profiles, as long as the methodology records which artifacts belong to which purpose.
The later load-generator article must also define whether load is open-loop or closed-loop, how client saturation is detected, how timing is recorded, how errors are counted, and how coordinated-omission risk is handled before any latency comparison is accepted. Java diagnostics can explain the server side only if the client side is controlled well enough to trust the measurements.
Acceptance Criteria for the Later Java Implementation
This article does not generate a Helidon project, build a JAR, run a load generator, or produce benchmark results. It defines the Java side of the contract. The runnable benchmark package is deferred until the series defines the full service contract, implementation plans, load-generator validation, execution method, reproduction requirements, and analysis method.
A later Java result is not accepted unless the Java implementation and run artifacts satisfy these gates:
The service implements the finalized Article 02 endpoint contract exactly, including JSON request rules, success responses, error responses, media-type handling, request body limit, logging posture, and TLS posture.
The service uses Helidon SE, and the manifest records the exact framework version and resolved dependency set used in the run.
The run records the exact JDK provider, version, build, architecture, runtime properties, system settings, effective JVM flags, heap policy, GC policy, available processors visible to the JVM, and any CPU or memory limits imposed by the execution environment.
The measured Java runtime variants are explicitly identified Oracle-built JDK variants unless a later scope change defines and validates additional runtime evidence separately.
The request-handling model is declared as platform threads, virtual threads, or another explicitly documented Helidon- and JDK-supported model, with evidence that the intended model was active.
Platform-thread and virtual-thread variants are included only when the selected Helidon SE release documents both modes in a way that allows the request-handling model to change without unrelated framework, endpoint, server-architecture, or JVM-policy changes.
Ordinary JVM execution, Leyden-related startup and warmup behavior, GraalVM Native Image, and checkpoint and restore workflows remain separate execution models unless a later article defines a distinct variant.
The run captures GC logs when required by methodology, process metrics, request metrics, warmup and measurement timestamps, and manifest links to artifacts.
Representative diagnostic runs include Java Flight Recorder where the methodology enables it, and selected profiler slices where platform support and permissions allow them.
The result does not compare against Go until the Go contract, load-generator contract, execution protocol, and analysis method are complete.
The smallest evidence-capture shape looks like this:
mkdir-p artifacts logs
java -version > artifacts/java-version.txt 2>&1
java
-XX:+PrintFlagsFinal
-version > artifacts/jvm-flags.txt 2>&1
Passing those commands is not enough to validate a benchmark. It only demonstrates the posture: runtime identity and effective flags are captured before results are reviewed.
If a later Java run is missing runtime identity, framework identity, request-handling evidence, warmup boundaries, diagnostics required by the methodology, or endpoint conformance, the run is not surprising. It is invalid.
Handoff to the Go Contract
The Java side is now specified enough to constrain later implementation work.
Java means Helidon SE. Runtime labels require exact JDK evidence. Virtual threads are a request-handling model. Leyden-related behavior is conditional and separate. JVM tuning is a hypothesis. Diagnostics and manifests gate results.
The next article applies the same discipline to Go.
That matters because Go has its own ways to drift. A compact net/http service can be easier to inspect, but it can still allocate differently, parse differently, validate differently, return different errors, or perform a different amount of work in the extraWork path. The Go implementation and tuning plan must be held against the same Article 2 service contract.
Java is specified here. Go is specified next. Results come later.
Conclusion: Make Java Auditable Before Measuring It
A defensible Go-versus-Java benchmark cannot leave Java undefined.
For this series, Java is a Helidon SE implementation of the Article 2 service contract, run on explicitly identified JDK variants, with a declared request-handling model, documented startup and warmup boundaries, testable JVM tuning hypotheses, required diagnostics, and manifest-backed evidence.
That does not make Java faster or slower. It makes the later Java result reviewable.
If you are building application services that depend on databases, model gateways, vector search, or other external systems, that is the useful habit to carry forward. Before comparing runtimes, define the service boundary. Before tuning, prove equivalence. Before publishing charts, capture the runtime evidence. Then, when results arrive, you can argue about the data instead of arguing about what was measured.
async-profiler for optional representative CPU, allocation, and wall-clock profiling slices after platform compatibility is validated.
]]>https://redstack.dev/2026/10/16/defining-the-java-helidon-benchmark-contract/feed/04848Working with AI Agents in your team
https://redstack.dev/2026/10/15/working-with-ai-agents-in-your-team/
https://redstack.dev/2026/10/15/working-with-ai-agents-in-your-team/#respondThu, 15 Oct 2026 16:30:17 +0000https://redstack.dev/?p=4920Continue reading →]]>Recently, I was lucky enough to be invited to give a short presentation on blended teams, and I wanted to share some of my thoughts with you, dear reader!
What is a “blended team”? I am defining it as a team that has both human and AI workers who are collaborating on the same goals and tasks.
As you know, AI is good at some things, and not so good at others. You could say “when it’s good, it’s very, very good; but when it’s bad, it’s very, very bad” (wink to Henry Wadsworth Longfellow).
Adding AI to a human team does not guarantee better performance.
The diagrams below, from arXiv:2507.09089v2 [cs.AI]Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity – Joel Becker, Nate Rush, Elizabeth Barnes, David Rein, present an interesting finding from the domain of software development: on average, experts tend to dramatically over-estimate how much AI assistance will speed up development. This study found that the estimates ranged from a 10% to 50% reduction in time – but the actual observed results were that tasks took up to 40% longer when AI assistants were used.
While developers estimated that AI assistance would enable them to reduce the time required for a task, as shown in the diagram below from the same study, the result was that they in fact took significantly longer when using AI.
Why is this the case? What’s going on here?
I’d like to offer the hypothesis that AI (and Generative AI in particular) is very good at doing things that have been done before, but much worse at doing something novel. This makes a lot of sense (to me, at least) if you consider that these models have been trained on very large corpora of existing code, and that they work by probabalistic prediction of the next token. So a model that has seen many examples of how to implement a particular type of requirement is likely to do a very good job of implementing that requirement. But, if you ask a model to implement something new, that it has not seen any, or many, examples of – it’s not going to do as good a job on that.
Another important thing to consider is the quality of the code the models were trained on. Charles Babbage called it way back in 1820 – garbage in, garbage out. And every developer knows, this is still very relevant today. If you consider that most of the code that the models were trained on is not what we would consider “good” – then you might not be surprised that the code they generate is also not “good”. Here’s some charts I pulled out of a paper showing distributions of some measurements of goodness across a wide sample of open-source code. The whole paper is very interesting and well worth a read.
Jin, Siyuan; Zhang, Mianmian; Guo, Yekai; He, Yuejiang; Li, Ziyuan; Chen, Bichao; Zhu, Bing; and Xia, Yong. “Software Code Quality Measurement: Implications from Metric Distributions.” 2023 IEEE 23rd International Conference on Software Quality, Reliability, and Security (QRS), 2023, pp. 488–496. https://doi.org/10.1109/QRS60937.2023.00054
Quantity is not quality
Consider another example – AI assisted detection of security vulnerabilities. Models like Mythos and Fable can detect many more vulnerabilities that we ever did before them using human review and our pre-existing tools. But on analysis, we find that a lot of those issues detected (at least in my experience) were poor quality, false positives, or just duplicates of issues that we found with our existing tools. An enormous amount of human work is needed to review the output of these models and separate the signal from the noise.
With the widespread use of AI in this area, there also came a massive amount of work for software developers to review, categorize and address these issues. We’ve seen a spike in CVEs since the availability of these models, as shown in the diagram below, created from public CVE data reported by cve.org – note that this data set is up to end of June 2026. No one really knows if that trend will continue upwards – my educated guess is that all of the activity by security researchers and developers will result in a lot of issues being fixed, and we will possibly see that level off and start to drop again, as the industry as a whole gets more focused on fixing issues, and adapts our development, testing and release processes to catch more issues before shipping code.
We should think about tasks, not jobs, that AI can do.
There’s a lot of talk about AI replacing jobs, but I think it is much better to think about tasks that AI can do, not whole jobs. We all know that the job description rarely, if ever, actually describes the real job. There are a lot of tasks that people do that don’t make it into the job description. I don’t like to think about using AI to replace a person’s job, but instead to think about which individual tasks we could use AI for – tasks where we would get an improvement (in time, quality, etc.) and which would let the person focus more time on the more difficult (less automatable) tasks.
So what tasks are AI models good at? Here’s a synthesis from a number of studies (see the citations at the end of this article):
In my own personal experience, I’ve found that AI is really good at things like doing research, fact checking, writing code (for known patterns, and with strong guardrails), scanning for vulerabilities, and less good at things like writing prose, creating graphics, making decisions, and so on. Human verification is essential for all AI outputs, but especially whenever errors are costly, context is hidded or judgement defines success.
Here’s a finding from a study that looked at usage of Copilot for various tasks and how successful that usage was for different kinds of tasks.
arXiv:2507.07935v6[cs.AI] Working with AI: Measuring the Applicability of Generative AI to Occupations – Kiran Tomlinson, Sonia Jaffe, Will Wang, Scott Counts, Siddharth Suri
AI does not remove work – it changes the mix
A very interesting study by Becker et al clearly demonstrates how the amount of time spent of different tasks changes when AI is used. Interestingly, the total amount of work is not necessarily the same, this looks only at the percentages, not the total.
arXiv:2507.09089v2[cs.AI] Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity – Joel Becker, Nate Rush, Elizabeth Barnes, David Rein
This is supported by other studies which found that the total amount of time increased. Here are some findings from one such study in the domain of open-source software development:
And here are some findings from a study on professional writing – total time reduced but the amount of time spent of each part of the work changed:
Generation speed is not delivery speed
Even if AI can reduce the amount of time it takes to write code from weeks to minutes – that does not mean I can ship the code and pass on that time gain to my end users. I still need to have people review the code, and I still need to do all the other security, compliance, and release management tasks. So while an individual task might be faster, my wall clock time is not necessarily impacted.
I love a poster I saw at a ballet school which read “Hard work is not for everyone” – I think that’s a very true statement. Using AI is easy, anyone can do it. But using AI well is a very different thing – and I think it is fair to say that most people probably won’t invest the time and effort to learn how to use AI well. This means that a lot of AI applications are going to be sub-par. You can easily find evidence for this – from the hype merchants publishing YouTube videos claiming to show you how to build an AI application in “five minutes”, to the high visibility failures like those showcased in “12 famous AI disasters”, Thor Olavsrud, CIO Magazine https://www.cio.com/article/190888/5-famous-analytics-and-ai-disasters.html and I suspect that you have personal experience of talking to an AI and finding its ability to actually “help” to be very poor.
Trust is vitally important in AI, and reputation damage and financial penalties are very real risks.
You won’t get it right the first time
Using AI “well” means things like understanding how the models work, comparing the performance of different models and hyper parameter settings for your specific use case and possibly corpora, implementing guardrails and retries, using techniques like planning and reflection, building and using evaluations, knowing how and when to use different kinds of memory, using skills, and so on. No matter how good you are, I’d argue that you won’t get it right the first time, and you need a continuous improvement loop.
It’s important to collect inputs and outputs, and then to do human reviews, and provide feedback about what is good and what bad. This data can be used to implement improvements, so that in essence the application ‘learns’ over time how to do the task right.
The handoff is critical
You need a mechanism to route and track tasks. AI can work faster than people. You need a way to queue up tasks so that it can pick form the queue based on whatever criteria are appropirate, maybe the token quota for example. If a task is not clear, it should be able to ask questions before starting work – so you need a way to allow it to assign a task back to a human to get more information. You should use techniques like guardrails and adversial reviews (ideally with a different model) to control quality.
So when is AI going to excel?
I think that this is a good litmus test to apply when trying to identify tasks that AI will be able to excel at:
Smaller, well-defined tasks with clear context, strong guardrails, and a strong definition of “right”
Tasks that do not require novel thought or complex decision making
Clean boundaries and handoffs between tasks
Repeatable, high-volume tasks
Continuous improvement feedback loop
We have a huge amount of opportunity ahead of us. Here’s an interesting finding from an Anthropic study that compares the opportunity in various industries to the actual observed usage today:
There’s lots of very active research in this area I’ve shared a number of papers that I’ve read myself as well as some of my conclusions from my own personal experience. I’d love to hear your thoughts and experience, please hit me up in the comments.
[1] Noy, Shakked, and Whitney Zhang. “Experimental Evidence on the Productivity Effects of Generative Artificial Intelligence.” Science 381(6654), 2023. https://doi.org/10.1126/science.adh2586
[2] Brynjolfsson, Erik, Danielle Li, and Lindsey R. Raymond. “Generative AI at Work.” Quarterly Journal of Economics 140(2), 2025. First circulated as NBER Working Paper 31161, 2023. https://www.nber.org/papers/w31161
[3] Ishikane, Masahiro, Yuki Kataoka, Yasushi Tsujimoto, Yuki Moriyama, Yukimasa Matsuzawa, and Norio Ohmagari. “Efficacy of a Large Language Model Data Extraction System in Evidence Reviews for Emerging Infectious Diseases: A Randomized Crossover Trial.” Open Forum Infectious Diseases 13(7), 2026. https://pmc.ncbi.nlm.nih.gov/articles/PMC13393321/
[4] Khraisha, Qusai, Sophie Put, Johanna Kappenberg, Azza Warraitch, and Kristin Hadfield. “Can Large Language Models Replace Humans in Systematic Reviews? Evaluating GPT-4’s Efficacy in Screening and Extracting Data from Peer-Reviewed and Grey Literature in Multiple Languages.” Research Synthesis Methods 15(4), 2024. https://doi.org/10.1002/jrsm.1715
[6] Becker, Joel, Nate Rush, Elizabeth “Beth” Barnes, and David Rein. “Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity.” METR / arXiv preprint, 2025. https://arxiv.org/abs/2507.09089
[8] Kumar, Deepak. “SWE-PRBench: Benchmarking AI Code Review Quality Against Pull Request Feedback.” arXiv preprint, 2026. https://arxiv.org/abs/2603.26130
[9] Ribalta-Albado, Maria, and Pere-Pau Vázquez. “Evaluating LLMs’ Abilities to Create Charts, a Systematic Approach.” Computers & Graphics 135, 2026. https://doi.org/10.1016/j.cag.2026.104544
[10] Collier, Zachary A., Richard J. Gruss, and Alan S. Abrahams. “How Good Are Large Language Models at Product Risk Assessment?” Risk Analysis 45(4), 2025 (published online in 2024). https://doi.org/10.1111/risa.14351
]]>https://redstack.dev/2026/10/15/working-with-ai-agents-in-your-team/feed/04920Defining the Service Contract Before Comparing Go and Java
https://redstack.dev/2026/10/14/defining-the-service-contract-before-comparing-go-and-java/
https://redstack.dev/2026/10/14/defining-the-service-contract-before-comparing-go-and-java/#respondWed, 14 Oct 2026 16:08:02 +0000https://redstack.dev/?p=4843Continue reading →]]>Key Takeaways
Before asking whether Go or Java is faster, both services need to answer the same HTTP question. That means the same endpoints, request fields, validation rules, work-factor semantics, response JSON, and error behavior.
The benchmark contract defines equivalent externally specified work, not identical CPU instructions. extraWork drives a deterministic operation whose result affects a returned checksum, so conformance tests can catch many skipped or altered implementations.
JSON comparison should be strict about schema, values, types, and error codes, but not brittle about object member order or whitespace. Framework-default HTML, text errors, stack traces, and runtime metadata are contract failures for body-bearing responses.
Shared acceptance tests are the gate into later implementation and benchmark work. The Java/Helidon and Go services must pass the same contract before any benchmark result is admissible.
You can make two services look almost identical and still measure different work.
One implementation accepts an unknown JSON field and ignores it. The other rejects the request. One silently clamps a payload size that is too large. The other returns a validation error. One computes a checksum from generated bytes. The other computes it from a different buffer, or runs a loop that does not affect the returned result. One returns a framework-default text error. The other returns JSON.
If those services go into a benchmark, the chart is already compromised. The result might look like Go versus Java, but part of the difference could be request parsing, validation policy, payload generation, error handling, or a work loop that does not mean the same thing in both implementations.
So before asking whether Go or Java is faster, we need to make sure both services are answering the same question.
The first article in this series set a fairness rule: no benchmark result is admissible until the method and evidence chain are strong enough to support it. This series is scoped to a later single-machine benchmark method, but the exact operating system, kernel, CPU, memory, runtime versions, and isolation settings belong in the execution-method article and benchmark manifest, not in this service-contract article. Here, we define the language-neutral service behavior that the Java service and the Go service must satisfy at the HTTP boundary before either one is tuned, load-tested, or compared.
For developers building service-tier APIs around Oracle AI Vector Search, retrieval, embedding, reranking, or Oracle AI Database workflows, this boundary matters. A small application service often sits between clients, model calls, and Oracle AI Database. If two versions of that service validate different JSON, generate different payloads, or return different correctness artifacts, later runtime measurements are not about the runtime anymore. They are about drift.
This article does not publish benchmark results. It does not choose a faster runtime. It does not implement either service. It does not design the full load generator or run the benchmark package. We are defining the service behavior that later code must satisfy.
What This Article Defines, and What It Does Not Measure
A language-neutral service contract is the externally visible behavior both implementations must provide, expressed without depending on Java or Go internals. For this series, that means the behavior a client can observe over HTTP: endpoint paths, methods, request headers, request JSON, validation rules, response JSON, status codes, and error shapes.
HTTP gives us the shared vocabulary for methods, status codes, content, and representations. JSON gives us a shared request and response format. The contract uses those pieces to define observable behavior explicitly rather than letting framework defaults decide.
This article defines:
The endpoint set and request media type
The JSON request and response shapes
The request body limit
Payload-size and deterministic payload-generation rules
The meaning of extraWork
Validation rules, duplicate-field behavior, and unknown-field behavior
Success and error response schemas
JSON equivalence rules
Cross-implementation acceptance-test categories
It does not measure throughput, latency, memory, CPU, startup, warmup, garbage collection, scheduler behavior, Oracle AI Database query performance, model inference, or vector-search performance. Those questions belong later in the series, after the service contract, implementations, load generator, execution method, and analysis method are stable.
Later latency measurements also need their own load model, request scheduling policy, timeout policy, warmup plan, sampling method, and treatment of coordinated omission.
That distinction is not academic. It is the difference between a benchmark that can be challenged constructively and a benchmark that depends on trust.
What Endpoint Is Under Test?
For this benchmark contract, both services expose the same two endpoints: GET /health and POST /work.
GET /health returns 200 OK, Content-Type: application/json, and the exact JSON object shown below. It exists to let scripts and acceptance tests confirm that the service is up and speaking JSON. It is not part of the measured work path. The response must not include extra fields.
{
"status":"ok"
}
No timestamp. No process ID. No framework name. No Java or Go version. Health is a readiness check for this contract, not a diagnostic endpoint.
HEAD /health follows HTTP HEAD semantics for the GET /health resource: it returns the same status and headers that GET /health would return, without a response body. The conformance suite treats that as protocol behavior, not as part of the measured work path.
POST /work is the endpoint under test. It accepts a JSON request body and returns JSON on success and on body-bearing failures.
For this benchmark contract, the request Content-Type must be application/json. For common-client compatibility, the service also accepts application/json; charset=utf-8. The JSON media type registration does not define a charset parameter; accepting that parameter here is a deliberate contract choice and does not change JSON processing. A missing Content-Type on POST /work is treated as an unsupported media type. The service returns 415 Unsupported Media Type with the agreed JSON error shape.
Successful and body-bearing error responses use Content-Type: application/json.
The request body for POST /work is also bounded. If the /work request content exceeds 4096 bytes after HTTP transfer decoding, the service returns 413 Content Too Large with the agreed JSON error shape. This limit is intentionally small because the request body contains only control fields, not the generated benchmark payload.
The rule is simple: for requests that can carry a response body, JSON in, JSON out.
That means success responses are JSON. Validation errors are JSON. Malformed request errors are JSON. Unsupported media type errors are JSON. Oversized request errors are JSON. Unsupported method errors are JSON, except where HEAD semantics require no response body. Unknown route errors are JSON. Framework-default HTML pages, plain-text errors, stack traces, redirects, or implementation-specific error documents are not acceptable for this benchmark contract.
Unsupported methods are also part of the boundary. If a client sends GET /work, the service returns 405 Method Not Allowed, includes Allow: POST, and returns the agreed JSON error shape. HEAD /work is unsupported and returns 405 Method Not Allowed with Allow: POST and no response body. If a client sends an unsupported body-bearing method to /health, the service returns 405 Method Not Allowed, includes an Allow header containing GET and HEAD, and returns the agreed JSON error shape. If a client sends POST /missing, the service returns a consistently defined 404 Not Found JSON error.
For the primary pure-service benchmark, request logging, TLS, compression, and tracing are off. Those are real production concerns, and later slices can measure them deliberately. They are not mixed into the primary service-equivalence contract. If a later scenario enables one of them, both implementations must use an equivalent configuration and pass conformance again.
HTTP status-code and method behavior in this contract follows the semantics defined by RFC 9110: HTTP Semantics. The endpoint names, response fields, and exact validation policy are benchmark contract choices.
What Does Each Request Contain?
The request body for POST /work is compact. It does not send a large payload over the wire. Instead, it tells the service how to generate deterministic bytes and how much deterministic work to apply.
The body must be a single top-level JSON object. Top-level arrays, strings, numbers, booleans, and null are invalid request shapes and return 400 Bad Request. Multiple JSON documents in one request body are also invalid.
A valid request looks like this:
{
"requestId":"case-0001",
"payloadSize":1024,
"seed":42,
"extraWork":10
}
Each field has a specific job.
requestId is a stable client-provided identifier. The service echoes it in a successful work response. It must be a JSON string with length 1..128.
payloadSize is the requested deterministic payload size in bytes. For this contract, it must be an integer between 0 and 131072, inclusive. That upper bound gives us payloads up to 128 KiB without putting large payload bodies into article examples or small conformance fixtures. A value below 0, a value above the maximum, a string such as "1024", or a fractional number fails validation.
seed is the input to deterministic payload generation. It must be an integer between 0 and 2147483647, inclusive. Keeping it in a conservative integer range avoids JSON number interoperability problems and makes the same fixture easy to represent in both Java and Go.
extraWork is a bounded work factor. It must be an integer between 0 and 100, inclusive. A value of 0 is valid and means “generate the payload and compute the initial correctness artifact, but apply no extra repeated work.”
Numeric fields must be JSON integers, not quoted numeric strings or fractional values.
Unknown fields are rejected. That may feel strict, but it is useful strictness. If the Go service silently accepts "payload_size" while the Java service rejects it, the two services no longer have the same contract. If one parser ignores "debug": true and the other fails, the benchmark has hidden drift. During conformance, extra fields are a 400 Bad Request.
Duplicate member names in the top-level /work request object are also invalid for this contract. The request schema does not contain nested objects; if nested objects are added later, the duplicate-member rule must be extended explicitly.
JSON syntax and interoperability rules are defined by RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format. RFC 8259 describes JSON objects as unordered collections, says object names should be unique, and notes that behavior can be unpredictable when parsers receive duplicate names. This benchmark contract removes that ambiguity by rejecting duplicate top-level request fields before field validation.
The services should not silently accept a request body such as this:
{
"requestId":"case-0001",
"payloadSize":1024,
"payloadSize":2048,
"seed":42,
"extraWork":10
}
Test fixtures use unique field names. Conformance tests include duplicate-field cases to make sure both services fail them consistently.
How Is Payload Size Controlled?
The request does not carry the full payload. The service generates the payload deterministically from payloadSize and seed.
That choice keeps the benchmark focused. If the client sends a large JSON string, we are measuring request-body transport, JSON string parsing, escaping behavior, memory copies, and possibly different decoder strategies. Those can be useful in another benchmark, but they are not the shape we need here.
For this contract, the input tells the service how many bytes to generate. Both implementations must use the same language-neutral payload-generation algorithm. They must not call a runtime-specific random API and assume the output will match.
The contract can be expressed this way:
state = unsigned64(seed)
for i from 0 to payloadSize - 1:
state = (state * 6364136223846793005 + 1442695040888963407) modulo 2^64
buffer[i] = (state >> 56) & 0xff
Both implementations must use the same constants, unsigned 64-bit wraparound behavior, byte extraction, and iteration count. The same payloadSize and seed must produce the same byte sequence in Java and Go.
That gives acceptance tests a clean target. A test case can say, “For payloadSize = 1024 and seed = 42, both services must generate the same buffer and return the same checksum after the same work factor.” We do not need to inspect the buffer over HTTP; the returned correctness artifact shows whether the service produced the specified result.
What Does the Work Factor Mean?
This is the part of the contract most likely to make or break the benchmark.
extraWork is not a delay knob. It is not “run a loop for a while.” It is not “do whatever is convenient in each language.” It is the number of times the service applies a specified deterministic operation to the generated payload buffer, and the operation must affect the returned checksum.
A language-neutral sketch looks like this:
buffer = generatePayload(payloadSize, seed)
state = SHA-256(buffer)
repeat extraWork times:
state = SHA-256(state || buffer)
checksum = lowercaseHex(state)
The || symbol means byte concatenation: the current 32-byte hash state followed by the generated buffer. The final checksum is the lowercase hexadecimal encoding of the final SHA-256 state.
This does not claim that Java and Go execute identical machine instructions. They will not. The JIT compiler, Go compiler, libraries, memory layout, CPU intrinsics, allocator behavior, and runtime scheduling can differ. Java and Go may also use different SHA-256 implementations. The contract requires equivalent externally specified work: both services generate the same buffer, apply the same deterministic operation the same number of times, and expose the resulting checksum so tests can verify the externally specified result.
That last point is important. If extraWork does not affect the response, an implementation could accidentally skip the loop and still pass a superficial status-code test. Because extraWork affects the returned checksum, conformance tests can detect many skipped or altered implementations of the specified work. That does not prove instruction-level equivalence; it proves that the observable result matches the contract.
Checksum examples in this article are format placeholders, not test vectors. Conformance fixtures must use complete expected checksum values computed from the published payload-generation and work-factor algorithms.
What Does a Successful Response Look Like?
A successful POST /work response returns 200 OK, Content-Type: application/json, and a stable JSON body.
The success schema has this shape. The checksum value below is a format placeholder, not an expected value for the earlier request:
The placeholder checksum is not a test vector. A real conformance fixture must use a complete lowercase SHA-256 hex string independently computed from the published payload-generation and work-factor algorithms.
The fields are deliberately limited.
requestId must match the request. payloadSize must match the accepted request value. extraWork must match the accepted request value. checksum must be derived from the deterministic payload and the work-factor operation. ok is true for a successful work response.
The response intentionally does not echo seed; the seed is validated and used to derive checksum, but it is not part of the success response schema.
The response does not include runtime metadata. No thread ID. No goroutine ID. No hostname. No process ID. No memory statistics. No framework name. No timestamp. No JDK or Go version. Those can be useful in logs, manifests, diagnostic endpoints, or benchmark artifacts, but they do not belong in the correctness response.
Why so strict? Because correctness responses are compared across implementations. If Java returns "framework": "Helidon" and Go returns "framework": "net/http", either the comparison has to ignore fields or the services fail. Ignoring fields too broadly can hide real differences. The cleaner choice is to keep the response schema focused on the contract.
How Should Validation Failures Behave?
Validation behavior is part of the benchmark, not an implementation detail.
If invalid input changes which requests are accepted, how much work is performed, or what response body is serialized, it can contaminate later measurements. So the contract defines both status code and JSON shape for responses that carry a body.
A field validation error looks like this:
{
"error":{
"code":"INVALID_REQUEST",
"message":"payloadSize must be between 0 and 131072",
"field":"payloadSize"
}
}
For this contract, request-shape and scalar validation failures use 400 Bad Request. That includes missing required fields, wrong JSON types, out-of-range numeric values, unknown fields, duplicate top-level request fields, and invalid requestId values.
Malformed JSON also returns 400 Bad Request, with the error code MALFORMED_JSON and a field value of null. A body containing multiple JSON documents is treated the same way.
Unsupported request media types return 415 Unsupported Media Type. Request bodies larger than 4096 bytes return 413 Content Too Large. Unsupported body-bearing methods return 405 Method Not Allowed, include an Allow header listing supported methods for that target resource, and return the agreed JSON error shape. HEAD responses follow HTTP no-body semantics. Unknown routes return 404 Not Found.
A non-field error uses the same envelope:
{
"error":{
"code":"UNSUPPORTED_MEDIA_TYPE",
"message":"Content-Type must be application/json or application/json; charset=utf-8",
"field":null
}
}
The contract uses these machine-readable error codes:
MALFORMED_JSON for syntactically invalid JSON or multiple JSON documents in one request body.
INVALID_REQUEST for a valid JSON body with an invalid top-level shape, missing required field, wrong type, out-of-range value, invalid requestId, unknown field, or duplicate top-level request field.
UNSUPPORTED_MEDIA_TYPE for missing or unsupported Content-Type on POST /work.
CONTENT_TOO_LARGE for a /work request body larger than 4096 bytes.
METHOD_NOT_ALLOWED for unsupported methods on known routes.
NOT_FOUND for unknown routes.
Conformance fixtures compare HTTP status, machine-readable code, field, and JSON shape when the response carries a body. The message value must be a non-empty string, but basic conformance does not require exact message equality unless a fixture explicitly opts into it. If one service returns INVALID_REQUEST and the other returns bad_request for the same fixture, that is a contract failure.
When a request has multiple problems, conformance tests use this precedence order unless a fixture explicitly states otherwise:
This order keeps routing and protocol failures separate from JSON-shape failures. Basic conformance fixtures should still prefer one failure per request, but the precedence rule prevents accidental drift when multi-fault cases appear.
The error object is a small custom JSON shape. It is not claiming RFC 9457 Problem Details for HTTP APIs compliance. If a future version adopts Problem Details, it should do so explicitly, including the appropriate media type and fields.
What Makes Two JSON Responses Equivalent?
JSON response comparison should be strict enough to catch real differences and flexible enough to avoid false failures from incidental serialization details.
A response with the same fields in a different order is equivalent:
That object is semantically equivalent to the earlier success-response shape if all required fields, values, and JSON types match. Object member order and insignificant whitespace are not part of correctness.
But these differences must fail conformance:
"payloadSize": "1024" instead of "payloadSize": 1024
Missing checksum
Different requestId
Different extraWork
A checksum that does not match the deterministic payload and work factor
A different machine-readable error code for the same validation failure
Extra runtime-specific fields when the contract forbids them
A framework-default HTML or plain-text error body where JSON is required
Byte-for-byte JSON comparison is too brittle. A loose “does the response contain a few expected fields somewhere?” comparison is too weak. The target is structural comparison: required field names, JSON types, values, error codes, and status behavior must match.
The language-neutral contract defines the same request, validation rules, deterministic work, and JSON response before Java/Helidon and Go implementations can enter benchmark execution.
How Do Acceptance Tests Prove Equivalence?
Acceptance tests are the gate between contract and benchmark.
The test runner is not the important part yet. It could eventually be a small custom tool, a script, or a test suite in a language chosen for the benchmark harness. What matters is that the same cases run against both implementations and compare the same expected behavior.
The acceptance cases should cover the ordinary path and the annoying edges.
For the happy path, the suite needs a valid minimal request, representative small and medium payloads, the maximum allowed payloadSize, extraWork = 0, and the maximum allowed extraWork. The maximum-payload case does not need to combine maximum payloadSize with maximum extraWork in a basic conformance run. The point is to prove the boundary values and deterministic behavior, not to turn contract validation into a stress test.
For determinism, the same request sent repeatedly must return the same stable fields and checksum. The same test vector sent to Java and Go must return JSON-equivalent responses. Object member ordering must not affect the comparison.
For validation, the suite needs missing required fields, wrong JSON types, negative payloadSize, payloadSize = 131073, invalid requestId, negative extraWork, extraWork above 100, malformed JSON, multiple JSON documents, duplicate fields, unknown fields, unsupported media type, oversized body, unsupported method, and unknown route.
For error equivalence, both services must return the same status code, same machine-readable error code, same required error fields when a body is allowed, and no framework-default HTML, stack traces, or plain-text errors.
For protocol behavior, GET /health must return stable JSON, HEAD /health must follow HEAD semantics for the health resource, POST /work must require JSON, response Content-Type must be consistent with the contract, and 405 responses must include the appropriate Allow header.
Passing these tests does not prove performance fairness by itself. It proves the functional contract. Performance fairness also needs implementation review, allocation analysis, tuning discipline, load-generator validation, environment capture, run protocol, and statistical analysis. Those appear later in the series.
But this is the gate that comes first. Java and Go can differ internally. They can use different libraries, runtime strategies, allocators, diagnostics, and tuning flags. If they cannot produce the same observable behavior for the same fixtures, they do not enter benchmark execution.
The Handoff to the Implementations
The contract gives the implementation articles a narrow job: build services that satisfy the same externally visible behavior.
The Java/Helidon implementation and the Go implementation can choose idiomatic libraries, data structures, and runtime configuration where the contract leaves room. They cannot change endpoint paths, request fields, validation rules, deterministic payload generation, extraWork semantics, success response fields, error response shape, or JSON equivalence rules to make one implementation easier.
That may sound restrictive, but it is what makes the later comparison useful. Once both services pass the same acceptance suite, the benchmark can move on to the next questions: how the services are implemented, how the load generator is validated, how the environment is captured, how runs are executed, and how results are analyzed. Until then, there is no Go-versus-Java result to interpret. There is only a contract to satisfy.
References
The contract choices in this article use standards and product documentation as context, but the endpoint names and field names are benchmark design decisions.
RFC 9110: HTTP Semantics defines the HTTP vocabulary for methods, status codes, content, and representation metadata used by the contract.
RFC 9457: Problem Details for HTTP APIs provides context for standardized HTTP API error responses, although this article uses a smaller contract-specific error shape.
Oracle AI Database provides the database platform context for AI application services and database-backed workflows.
Oracle AI Vector Search provides the high-level context for service-tier APIs around vector search and AI application workflows.
]]>https://redstack.dev/2026/10/14/defining-the-service-contract-before-comparing-go-and-java/feed/04843A Fair Go and Java Benchmark Starts With a Contract
https://redstack.dev/2026/10/12/a-fair-go-and-java-benchmark-starts-with-a-contract/
https://redstack.dev/2026/10/12/a-fair-go-and-java-benchmark-starts-with-a-contract/#commentsMon, 12 Oct 2026 19:33:55 +0000https://redstack.dev/?p=4832Continue reading →]]>Key Takeaways
This first article does not publish benchmark results. It defines the contract that later Go net/http and Java Helidon SE runs must satisfy before any chart is worth discussing.
Fairness in this series means testable equivalence: the same endpoint behavior, payload rules, validation and error handling, plus declared CPU, memory, logging, TLS, and process-topology choices.
The primary benchmark is a bounded single-machine Linux service-under-test benchmark. It is relevant to developers building AI services with Oracle AI Database, but it does not measure database execution, model inference, Kubernetes, autoscaling, service mesh behavior, or cloud-provider performance unless those appear as separately labeled slices.
If we include multiple JDK builds, a distinct request-handling mode, a Leyden-related startup or warmup path, or GraalVM Native Image, each one will be labeled as its own runtime shape with exact versions, flags, generated artifacts, and run conditions.
You have probably seen this pattern before. A benchmark shows a compact Go service next to a compact Java service. The chart is interesting. The conclusion is tempting. Then the comments get more useful than the chart.
How many cores were assigned? Was the load generator the bottleneck? Was the Go implementation doing the same work as the Java implementation? What did memory look like? What did garbage collection do? Which JDK build was used? Did virtual threads matter, or were they just present? If the selected JDK includes startup or warmup features associated with Project Leyden work, did they change startup, warmup, first-request behavior, footprint, or steady-state behavior? Were the runs long enough? Were there enough repeats? Were the statistics strong enough to support the claim?
Those are not annoying questions. They are the right questions.
This series follows up on that kind of Go-versus-Java service comparison: a Go net/http service on one side and a Java Helidon SE service on the other. That shape is worth investigating, but only if the method is strong enough to carry the result. The follow-up needs to answer the questions that usually get buried under the chart: CPU and core disclosure, memory use, GC behavior, JDK build clarity, request-handling behavior where applicable, startup or warmup features where applicable, load-generator validity, implementation equivalence, longer runs, more repeats, and statistical treatment.
So Part 1 does not publish new numbers. No old CSV, old chart, or previous result claim is evidence for this run. This article defines the rules a later run must satisfy before any result deserves attention.
If you are building AI applications that use Oracle AI Database, that distinction still matters—but the primary benchmark measures the application-tier service boundary, not database behavior. A retrieval API, embedding gateway, reranking service, feature-enrichment service, or application-tier vector-search facade can spend meaningful time in ordinary service code before and after it touches a database or a model. Runtime efficiency, tail behavior, warmup, memory pressure, and operational visibility still affect cost and reliability.
But if we mix database latency, model inference, service mesh overhead, and runtime behavior into one chart too early, we will not know what we measured.
The first move is to narrow the question.
Why This Follow-Up Starts With a Benchmark Contract
A benchmark contract is the set of rules that determines what is measured, which variants are included, how implementation equivalence is checked, how runs are accepted or rejected, and how analysis is performed before charts appear.
That sounds formal, but the idea is simple: write down the method before you see the result.
Without a contract, benchmark discussion drifts quickly. One side argues that the Go service is smaller. Another side argues that the Java runtime has better optimization and diagnostics. Someone asks whether the request-handling model changed the result. Someone else asks whether the load generator was saturated. Eventually the conversation becomes a proxy argument about language preference instead of a concrete discussion about a specific workload.
Our thesis is deliberately narrower: a useful Go-versus-Java service benchmark starts with a contract, not a chart. We will define equivalent work, fair runtime variants, measurement rules, and acceptance gates before publishing results, so later performance claims can be judged against a declared method rather than accepted on trust.
The contract has to answer a few practical questions before any chart is allowed:
What service behavior must the Go and Java implementations provide?
Which runtime shapes are being compared?
Which choices are fixed for the primary run, such as logging, TLS, CPU allocation, memory policy, and process topology?
What correctness tests prove that both implementations do the same externally visible work?
What evidence shows that the load generator has headroom?
Which warmup and steady-state windows define the measurement?
How many repeats are required, and what makes a run invalid?
Which raw artifacts connect the final chart back to source, build, runtime, machine, command, and analysis rule?
That list is the benchmark contract in plain language. A script producing numbers is not enough. A valid result has to trace back to the source revision, build, runtime, machine, command, measurement window, raw output, and analysis rule that produced it.
That dependency chain is the whole point of the series.
We define the benchmark contract in Articles 1–8 before publishing fresh results in Article 9 and interpreting the safe conclusions in Article 10.
The benchmark manifest for accepted runs will record the exact Go, JDK, Helidon, Linux, hardware, and tool versions used, including details that affect interpretation such as kernel version, CPU policy, and whether the service is running directly on the host or inside a constrained environment.
Which Go and Java Runtime Shapes Are Included
The comparison in this series is not “Go versus Java” in the abstract. That framing is too broad to be useful.
The Go side will use Go’s standard-library net/http package. That keeps the baseline focused on the built-in HTTP server path and avoids introducing third-party router or middleware choices into the primary comparison. Real Go services often include routers, middleware, validation libraries, and observability agents, and that is fine. This benchmark starts with the standard-library service boundary because it keeps the baseline small enough to audit.
The Java side will use Helidon SE, the selected Java service framework for this series, so the benchmark compares one declared Java service shape rather than the broader Java framework ecosystem. Spring Boot, Quarkus, Micronaut, and other stacks matter in real systems, but adding them here would change the question. This series is about Go net/http and Java Helidon SE under a declared service contract.
We will not report the Java side as just “Java.” If multiple JDK builds are included, each Java result will identify the JDK distribution or build provider, version, build identifier, command line, JVM flags, and support or licensing label used for that slice where that label affects interpretation. The question is not whether a label is faster in the abstract. The question is how the same Helidon SE source behaves under the specific JDK builds declared in the manifest.
Virtual threads are part of that Java service-shape discussion, but they need careful framing. JEP 444 delivered virtual threads in JDK 21. They are most relevant when the service model uses many concurrent blocking operations, especially I/O-bound work. They let developers write straightforward blocking-style code while supporting high concurrency more efficiently in workloads that spend time waiting.
They should not be treated as a general throughput or latency improvement for CPU-bound handlers. CPU-bound handlers still need CPU. If a request handler is mostly serialization, checksum work, or allocation pressure, the virtual-thread story may look different from a service that spends much of its time waiting on blocking I/O.
So we will treat the Java request-handling model as something to verify and measure, not something to assume. We will document the selected Helidon version, JDK version, server configuration, and request-handling model before applying labels such as platform threads, virtual threads, or default Helidon behavior. If that combination provides a distinct, supported, reproducible virtual-thread service shape, that slice will be labeled separately. If virtual threads are simply part of the selected Helidon shape, the manifest will say so instead of pretending that “Java” is a single opaque runtime.
Project Leyden and related startup or warmup features get the same separate-label treatment, and only when the selected JDK provides a supported, reproducible path. Project Leyden aims to improve startup time, time to peak performance, and footprint. Related JDK work, such as JEP 483: Ahead-of-Time Class Loading & Linking, is relevant to startup and warmup questions, but availability depends on the selected JDK version and build.
Leyden-related JDK features and GraalVM Native Image are different technologies. GraalVM Native Image ahead-of-time compiles Java applications into native executables. Leyden-related JDK features such as ahead-of-time class loading and linking are a different path. If either is included, we will label it separately, record the exact toolchain, flags, generated artifacts, and measurement scope, and avoid folding those results into the default JVM result.
For any startup or warmup feature associated with Leyden work, we will look especially at startup, warmup, footprint, and first-request behavior. If it appears to affect more than startup or warmup, the analysis will need artifacts to support that claim.
What Fair Means in This Benchmark
Fairness is not a slogan. It is a set of checks.
For this series, fair means the Go and Java services perform the same externally visible work: the same endpoint semantics, payload rules, validation behavior, error behavior, response shape, logging policy for the primary run, TLS policy for the primary run, declared CPU allocation, declared memory policy, and process topology.
That last part matters. One Go process versus one Java process is a different topology from several processes per runtime. A service with request logging disabled is different from one formatting a line on every request. Plain HTTP is different from TLS. A colocated load generator is different from a load generator running with enough isolated headroom to stay out of the server’s way. None of these choices is automatically wrong, but hidden choices make results hard to interpret.
Equivalent work comes before tuning. Each implementation must provide the same externally visible behavior before runtime-specific optimization is considered: request parsing, response generation, validation, error behavior, and any configured dependency interaction.
If the Go handler accidentally performs extra allocation in a work loop that the Java handler avoids, that is not a Go runtime result; it is a benchmark implementation bug until proven otherwise. If the Java service returns a different error body, validates different parameter ranges, or serializes a different payload, that is not a runtime result either.
The contract will require correctness tests before performance runs. Those tests need to compare outputs across implementations using stable request cases, not generated numeric row identifiers or one-off local observations. If an implementation changes for equivalence, the changed source becomes the benchmark source. Old results do not carry forward.
Fairness also means symmetrical restraint. We should not tune one runtime aggressively while leaving the other at casual defaults unless that is explicitly labeled as a tuned-versus-untuned comparison. We should not enable diagnostics inside the primary measurement path for one runtime and not the other unless the overhead is measured and accepted. We should not declare a run valid if the load generator is the thing being measured.
A useful benchmark should make unfairness difficult to hide.
What the Single-Machine Benchmark Measures
The primary benchmark will measure a declared single-machine Linux service-under-test workload. The service process or processes being measured will run on one declared Linux machine with a declared CPU, memory, and process policy. The load-generator placement will also be declared and validated in the run protocol because the client side can affect the result. If a separate client host is used for headroom, it remains part of the measurement harness, not a claim about distributed deployment.
Within that boundary, the benchmark will measure service behavior under controlled workload shapes: payload size, work factor, concurrency, CPU allocation, process topology, warmup, steady state, and resource pressure. It will report throughput and latency distribution together, because average response time without distribution data hides too much. It will also report CPU use, memory use, runtime behavior, startup, warmup, and steady-state behavior.
Warmup means the period before the measurement window where the service is allowed to initialize, compile hot paths, populate runtime structures, and settle into a more representative operating shape. Steady state means the measurement window after warmup, when the benchmark records the primary service behavior for that run.
For a JIT runtime, warmup is obviously important. For a non-JIT runtime, warmup can still matter because caches, connection state, allocator behavior, and CPU-frequency behavior can change early-run measurements.
Java diagnostic runs will include runtime telemetry where appropriate, such as GC behavior, allocation pressure, thread behavior, and selected Java Flight Recorder data. JDK tools such as jcmd can help capture runtime state in diagnostic runs, with exact commands recorded in artifacts. Profiling and diagnostics can add overhead, so diagnostic runs must stay separate from primary measurement runs when that overhead matters.
Go diagnostic runs will also capture runtime and diagnostic information where appropriate, using Go tooling such as pprof, runtime statistics, and tracing. Again, the point is not to drown the reader in profiles. The point is to avoid explaining a throughput or latency shape by guessing.
The load generator is part of the benchmark, not an afterthought. A service benchmark is not valid just because the server process is busy. The client side also needs headroom. If the load generator is CPU-saturated, cannot sustain the requested rate, or distorts latency measurement, the run is evidence about the test harness, not about Go versus Java service behavior.
The selected load generator must be validated for headroom and latency-measurement behavior. A fixed-rate tool such as wrk2, or another documented tool selected later, can help address coordinated-omission risk, but the benchmark must still prove that the client is not CPU-, network-, connection-, or scheduling-limited. Latency reporting will need distribution detail, not just a single average or p99. Tools and formats such as HdrHistogram are useful here because they preserve a fuller percentile spectrum.
The primary pure-service results will stay separate from secondary slices. TLS is a useful slice. Request logging is a useful slice. A real dependency, possibly an Oracle AI Database call, can be a useful slice. But those slices answer different questions.
If we add an Oracle AI Database dependency later, the result may reflect driver behavior, connection pooling, query shape, database execution, network locality, and runtime behavior together. That can be useful, but it should not be confused with the primary pure-service benchmark.
One more boundary matters: this is an end-to-end HTTP service benchmark, not a JVM microbenchmark. JMH is useful for JVM microbenchmarks, but it is not a replacement for measuring a service path through HTTP handling, payload work, runtime behavior, load generation, and resource use.
What the Benchmark Does Not Measure
The boundary is narrow on purpose.
We keep the primary benchmark inside a single-machine service boundary, so later results are useful without pretending to answer deployment, cloud, or distributed-systems questions.
The primary benchmark will not support conclusions about Kubernetes scheduling, autoscaling, service mesh behavior, multi-node networking, cloud-provider performance, distributed reliability, rolling updates, node cold starts, or production fleet operations. It will not compare cloud providers. It will not make claims about how a full distributed system behaves.
It also does not measure all Java frameworks or all Go frameworks. It does not measure universal language superiority. It does not measure model inference. It does not measure Oracle AI Database-dependent behavior, including database-side vector search, in the primary run. It does not tell you how a full retrieval-augmented generation stack behaves under production traffic.
That does not make the benchmark small in a bad way. It makes the benchmark interpretable.
If you are building an AI application on Oracle AI Database, you often need both kinds of information. You need database and model benchmarks for database and model questions. You also need application-tier service benchmarks for runtime, concurrency, warmup, memory, and operational questions. We start with the service boundary so that later, if a dependency slice is added, we can see what changed.
A benchmark that answers one question clearly is more useful than a benchmark that vaguely gestures at ten.
How the Series Gets From Contract to Results
This is a ten-part series because the method needs to be visible before the result.
Part 1, this article, defines the benchmark contract and the scope boundary. Part 2 defines the language-neutral service requirements: endpoint behavior, payload generation, work factor, response shape, validation, errors, and cross-implementation acceptance tests. Those requirements come before Go or Java implementation detail.
Parts 3 and 4 then constrain the implementations. The Java article covers the Helidon SE service shape, request handling for the selected Helidon and JDK combination, JDK runtime inputs if multiple builds are included, startup or warmup features where applicable, and Java diagnostics. The Go article covers the net/http implementation, the equivalence review, allocation behavior, Go runtime settings, and Go diagnostics.
Part 5 focuses on load generation. That includes request model, fixed-rate behavior, coordinated-omission risk, client headroom, and the evidence needed to show the load generator is not the bottleneck. Part 6 defines benchmark methodology: run protocol, CPU and memory policy, warmup, steady-state windows, invalid-run rules, resource capture, and traceability. Part 7 turns the method into execution artifacts: environment, versions, commands, manifests, run order, and raw outputs.
Part 8 defines analysis before results: canonical data shape, aggregation, uncertainty reporting, plot rules, outlier handling, and invalid-run handling. Only after those steps does Part 9 publish fresh benchmark results. Part 10 interprets what those results mean inside the declared boundary.
That order is deliberate. If the analysis rules are written after seeing the charts, the reader has to wonder whether the rules were chosen to make the charts look better. If the implementation contract is written after tuning, the reader has to wonder whether equivalence was enforced or assumed. If the load generator is validated after a surprising result, the reader has to wonder whether the harness is being rescued.
Part 1 publishes no benchmark results. Later result articles will include or link to manifests that identify the source revision, build commands, runtime versions, machine configuration, load-generator configuration, raw outputs, and analysis scripts used for each accepted run. Each accepted run must be traceable to:
The exact Go and Java source revision
The build commands and generated artifacts
The Go version, JDK distribution or build provider, JDK build identifier, and Helidon version
The runtime flags and process topology
The load-generator command and configuration
The Linux environment manifest for the machine
The warmup and measurement windows
The raw latency, throughput, CPU, memory, and runtime diagnostic files
The analysis script or notebook that produced the chart
This is how old charts and orphaned CSV files stay out of the evidence chain. They may explain why we are asking better questions, but they are not proof for the new run.
Acceptance Gates Before Results
A run does not count just because it completed.
The benchmark needs acceptance gates that reject bad evidence before it influences conclusions. Some gates are functional: the Go and Java services must return equivalent responses for the same valid requests and equivalent errors for invalid requests. Some gates are environmental: the machine, runtime versions, CPU topology, memory, operating-system state, and process topology must be captured. Some gates are methodological: warmup and steady-state windows must be declared before the run, repeat rules must be defined, and invalid-run reasons must be applied consistently.
A run does not count if the Go and Java services return different responses, the selected JDK build is not recorded, the load generator is saturated, the warmup period is missing, a repeat is discarded without a declared reason, resource data is missing, or raw artifacts cannot be traced back to source, build, runtime, and machine state.
That list is not exhaustive, but it shows the posture. Invalidity comes from contract violations, not from surprise. A run is not rejected because one runtime looks unexpectedly good or unexpectedly bad. It is rejected because it failed a rule that existed before the result.
Repeat aggregation also needs discipline. If multiple runs are collected, the series must say how they are combined and how uncertainty is shown. If a run is unstable, the instability is either a result to explain or a contract failure to document. It is not something to hide with a prettier chart.
Resource metrics must be interpreted with throughput and latency, not as a separate appendix nobody reads. A service that reaches high throughput by consuming much more CPU is different from one that reaches the same throughput with less CPU. A low-latency shape with high memory pressure has a different operational story from a low-latency shape with stable memory. GC pauses, allocation rate, heap behavior, and warmup matter because they explain why a service behaves the way it does under load.
This is especially relevant for AI application services. The expensive part of an AI system is not always the HTTP handler, but inefficient service code can still waste CPU that you would rather spend on database work, model calls, embedding pipelines, or concurrent users. The benchmark needs to report enough resource context to make that tradeoff visible.
The Questions This Series Will Answer
By the end of the series, you should be able to answer a tighter set of questions than “Which language is faster?”
Under this single-machine service-under-test workload, how do Go net/http and Java Helidon SE behave as payload size, work factor, concurrency, CPU allocation, and process topology change?
Does workload shape change the result? A small response with little work may stress the runtime differently from a larger payload, a more allocation-heavy path, or a higher-concurrency request pattern.
How much CPU and memory does each variant consume to produce its service behavior? Throughput without resource context is incomplete.
What are the Java runtime characteristics: GC frequency, pause behavior, heap behavior, allocation pressure, thread behavior, startup, warmup, and steady-state profile?
What are the Go runtime characteristics: allocation behavior, heap behavior, scheduler behavior, GC impact, startup, warmup, and steady-state profile?
Does the selected Java request-handling model matter for this workload? If it does, where does it show up: latency distribution, CPU use, memory use, concurrency behavior, warmup, or operational visibility?
If more than one JDK build is included, what changes, if anything, when the same Java source is tested with the same declared JVM settings and separately recorded JDK distribution, version, and build identifier?
Where do startup or warmup features associated with Leyden work help, if they are included: startup, warmup, first-request behavior, footprint, steady state, or not at all under this workload?
If GraalVM Native Image is included as a separate slice, what changes when the Java application is built and measured as a native executable rather than as the default JVM run?
Did both implementations perform the same work-factor calculation and payload handling under the language-neutral service contract? If an equivalence issue is found and corrected, which corrected source revision is used for the main run?
Does adding focused service behavior, such as TLS, request logging, or a real dependency, change the interpretation? If a dependency slice is added, which part of the result belongs to the service runtime and which part belongs to the dependency path?
Which conclusions are safe inside the single-machine service-under-test boundary, and which remain out of scope?
Those are the questions worth answering. Not because they produce a more dramatic chart, but because they make the chart harder to misunderstand.
References and Methodology Notes
These references support the terminology and scope used in this kickoff article:
The most useful thing this first article can do is refuse to rush.
Go offers a standard-library HTTP server and a common single-binary deployment style. Modern Java offers Helidon SE as one focused service framework option, virtual threads for suitable blocking-concurrency workloads, extensive JDK diagnostics, multiple JDK build choices, and ongoing work around startup, warmup, and footprint.
None of that decides the benchmark.
The benchmark has to decide the benchmark, and it can only do that if the work is equivalent, the runtime shapes are explicit, the load generator is valid, the environment is captured, warmup and steady state are separated, repeats are handled consistently, and uncertainty is reported honestly.
That is the contract. Next we define the language-neutral service requirements so Go and Java are asked to do the same work before either implementation gets tuned.
]]>https://redstack.dev/2026/10/12/a-fair-go-and-java-benchmark-starts-with-a-contract/feed/14832When GraphRAG Is Worth It: Travel Disruption Retrieval with Oracle AI Database 26ai
https://redstack.dev/2026/06/15/when-graphrag-is-worth-it-travel-disruption-retrieval-with-oracle-ai-database-26ai/
https://redstack.dev/2026/06/15/when-graphrag-is-worth-it-travel-disruption-retrieval-with-oracle-ai-database-26ai/#respondMon, 15 Jun 2026 19:40:20 +0000https://redstack.dev/?p=4696Continue reading →]]>
]]>https://redstack.dev/2026/06/15/when-graphrag-is-worth-it-travel-disruption-retrieval-with-oracle-ai-database-26ai/feed/04696How to Build a GraphRAG Travel Assistant with Oracle AI Database 26ai
https://redstack.dev/2026/06/15/how-to-build-a-graphrag-travel-assistant-with-oracle-ai-database-26ai/
https://redstack.dev/2026/06/15/how-to-build-a-graphrag-travel-assistant-with-oracle-ai-database-26ai/#respondMon, 15 Jun 2026 14:24:09 +0000https://redstack.dev/?p=4686Continue reading →]]>Grounded AI applications are hard to trust when the evidence is split across similar text, structured rows, and relationships. Flight disruption questions are a good example: a delayed traveler needs timing math, airport relationships, route alternatives, policy language, and a plain explanation that shows how the answer was reached. A basic RAG application can retrieve policy text, but it does not naturally understand that an inbound flight, a connection airport, an outbound segment, and an alternate route form a connected problem.
This tutorial builds a compact travel disruption assistant with Oracle AI Database 26ai, SQL property graphs, Oracle AI Vector Search, Python, and OpenAI. We will load staged tutorial CSVs shaped after OurAirports and BTS on-time performance fields, build a relational schema, define a SQL property graph, compare three retrieval modes, and generate a grounded answer to a missed-connection question.
The completed demo is intentionally small enough to inspect. It is not an operational airline recommendation system, and the included risk score is a deterministic tutorial ranking feature rather than a predictive model. The point is to show how graph-aware retrieval changes the evidence we can give an assistant.
What Is GraphRAG With Oracle AI Database 26ai?
GraphRAG combines graph traversal with retrieval-augmented generation. Instead of retrieving only text chunks that look semantically similar to the question, the application also follows relationships between entities: airports, flights, itinerary segments, connection rules, and candidate routes.
Oracle AI Database 26ai is a useful place to build this pattern because the same database can hold relational tables, vectors, and SQL property graph definitions. In this tutorial, policy chunks use vector retrieval, route facts stay in relational tables, and connected travel reasoning uses graph queries over the same stored data.
The demo calls OpenAI directly for embeddings and answer generation. The tutorial code keeps the OpenAI calls isolated in openai_provider.py, so the retrieval logic, schema, and graph queries remain clear.
Embeddings convert policy text and the user’s question into vectors so the database can compare meaning rather than only keywords. The stored policy vectors and the query vector must come from the same embedding model, because dimensions and numeric behavior are model-specific. If the OpenAI embedding model or configured embedding dimension changes, rebuild the stored policy vectors before comparing new queries with old rows.
Key Features of Oracle AI Database 26ai for GraphRAG
Oracle AI Database lets us keep structured, vector, and graph evidence close to the data. The demo uses a few features together rather than treating them as separate systems.
SQL property graphs
A SQL property graph exposes selected relational tables as vertices and edges. We model airports, passenger itineraries, and itinerary segments as vertices, then use route summaries, flight instances, and helper edge tables as relationships.
Oracle AI Vector Search
Policy chunks are stored with a VECTOR column and searched with VECTOR_DISTANCE(). The tutorial dataset has only a few policy chunks, so we keep the vector path simple and do not create an index in the runnable lab.
Relational constraints
Connection buffers, scheduled times, route risk scores, and passenger preferences are easier to inspect as relational rows. We use SQL for the pieces that should stay deterministic and explainable.
LLM-grounded answers
The final response is generated from retrieved evidence rather than from a free-form prompt. The OpenAI provider wrapper receives the question, evidence blocks, and explanation path, then returns an answer that the demo can inspect.
How to Get Started with Oracle AI Database 26ai GraphRAG
We will use the companion demo package generated with this tutorial. The public article shows the commands and representative snippets; the complete runnable files are in demo/demo_code_package.md and in the extracted demo workspace that accompanies this tutorial package.
Prerequisites:
Python 3.12.
Docker or a compatible Compose runtime for the included Oracle AI Database 26ai Free container.
Access to Oracle Container Registry with the database/free repository terms accepted.
An OpenAI API key, an OpenAI generation model, an OpenAI embedding model, and the embedding dimension used for the vector column.
The staged tutorial CSV files included in data/raw.
The companion demo provisions Oracle AI Database 26ai Free locally with compose.yaml. The container startup mounts sql/10-setup-user.sql, creates a least-privilege graphrag_demo user in FREEPDB1, and leaves the Python checkpoint scripts to create only application-owned tutorial objects. You still supply your own OpenAI key and model identifiers, but you do not need a pre-created Oracle schema. The Python examples use python-oracledb thin mode by default; thick mode is useful when an environment requires Oracle Client libraries or wallet-specific client features.
Create the environment from the extracted demo project root:
docker compose up -d
cp .env.example .env
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
Edit .env and replace only the OpenAI placeholders. The Oracle values already match the local Compose database and demo user created by the init SQL script. Do not commit .env, credentials, private endpoints, wallet files, or API keys:
Before you run the checkpoint scripts, look at the shared helper file. Most of the demo imports demo_common.py, so understanding it makes the rest of the workflow feel like a system instead of a series of magic commands.
@dataclass(frozen=True)
classSettings:
oracle_user: str
oracle_password: str
oracle_dsn: str
openai_api_key: str
openai_model: str
openai_embedding_model: str
vector_dimension: int
The Settings object separates database connectivity, OpenAI generation, and OpenAI embeddings. That separation matters because each part changes at a different pace. If the embedding dimension changes, the vector table must be rebuilt. If the generation model changes, the schema and graph queries can stay the same.
The environment loader also validates a bug-prone value early:
defload_settings() -> Settings:
# Keep the vector table shape aligned with the embedding model.
raiseRuntimeError("OPENAI_EMBEDDING_DIMENSION must be an integer")fromexc
ifdimension<=0:
raiseRuntimeError("OPENAI_EMBEDDING_DIMENSION must be greater than zero")
This is more than defensive programming. Vector search depends on a fixed dimension. A query vector with one dimension count cannot be compared against stored vectors with another, so a typo in .env should stop the run before any database rows are loaded.
The CSV fixtures are small tutorial extracts. They follow the field shape needed for the lab, but they are not real-time operational flight feeds.
Before loading them, inspect the shape. The staged airport file is intentionally tiny:
airport_code
airport_name
airport_type
municipality
region_code
JFK
John F Kennedy International
large_airport
New York
US-NY
ORD
Chicago O’Hare International
large_airport
Chicago
US-IL
SFO
San Francisco International
large_airport
San Francisco
US-CA
DEN
Denver International
large_airport
Denver
US-CO
DFW
Dallas Fort Worth International
large_airport
Dallas-Fort Worth
US-TX
The staged flight file keeps the delay and distance columns that the route summary uses later:
flight_date
carrier
flight_number
origin
dest
dep_delay
arr_delay
cancelled
distance
2025-01-03
OC
410
JFK
ORD
45
23
0
740
2025-01-04
OC
410
JFK
ORD
15
18
0
740
2025-01-03
OC
821
ORD
SFO
10
14
0
1846
2025-01-04
OC
821
ORD
SFO
62
70
0
1846
2025-01-03
OC
603
ORD
DEN
8
11
0
888
GraphRAG Travel Disruption Assistant Demo Project
The demo answers this question:
My flight from JFK to ORD is delayed by 45 minutes. I have a connecting flight from ORD to SFO. Can I still make it, and what should I do?
We will build three retrieval modes:
Mode A: plain policy RAG.
Mode B: policy RAG plus relational itinerary and route facts.
Mode C: policy RAG plus relational facts plus SQL property graph traversal.
The retrieval-mode diagram shows why the rest of the demo is organized as a comparison. Each mode adds a kind of evidence: policy text, structured itinerary timing, and finally the graph path that exposes the DEN alternative.
The route graph is not abstract. It connects a delayed JFK to ORD segment, an at-risk ORD to SFO segment, and a ranked ORD to DEN to SFO alternative.
The map outline is derived from Natural Earth public-domain vector data, and the airport nodes use the latitude and longitude values from the staged airport fixture.
Basic
Step 1: Check the environment
First, run the environment check. It verifies required environment variables and database connectivity without printing secrets.
python 00_check_environment.py
Expected output:
Required database variables: present
OpenAI configuration: present
Database connection: OK
Database identity: <OracleAIDatabasebanner>
Environment check: OK
The check does not print secret values. It only confirms that the names needed by demo_common.py and openai_provider.py are present.
The check script is intentionally small. It calls the same settings loader used by later scripts and runs a banner query against the database. Treat it as a contract test for the workspace: if this step fails, fix the environment, dependency installation, or database connectivity before debugging graph SQL or answer generation.
Step 2: Create the schema
Next, create the database objects. The schema includes airports, flight instances, route summaries, passenger itineraries, itinerary segments, policy chunks, and helper edge tables.
python 01_create_schema.py
The script starts by dropping old demo objects. That makes the lab repeatable while you are learning:
This is a tutorial reset pattern, not a production migration pattern. In production you would use controlled migrations and narrower privileges. Here, the point is to let you recreate the same schema, reload the same data, and compare retrieval modes without hand cleanup.
The create_tables() function creates three kinds of objects:
Entity tables such as airports, passenger_itineraries, and itinerary_segments.
Evidence tables such as flight_instances, route_summaries, and policy_chunks.
Helper edge tables such as itinerary_has_segment_edges, segment_connect_edges, and segment_alternative_route_edges.
The policy_chunks table is where vector search enters the model:
CREATETABLE policy_chunks (
chunk_id VARCHAR2(50)PRIMARYKEY,
policy_key VARCHAR2(80),
title VARCHAR2(200),
content VARCHAR2(2000),
is_synthetic NUMBER(1),
source_note VARCHAR2(500),
embedding VECTOR(<embedding dimension>, FLOAT32)
);
The vector dimension comes from OPENAI_EMBEDDING_DIMENSION, so the table is aligned with the embedding model supplied by the environment. The table also keeps readable policy text next to the vector so the final answer can cite text that a reader can inspect.
The property graph helper edges keep the model explicit. For example, itinerary-to-segment and segment-to-segment relationships are represented as dedicated edge tables rather than reusing a vertex table as an edge source.
CREATETABLE segment_connect_edges (
edge_id NUMBER GENERATED ALWAYS ASIDENTITYPRIMARYKEY,
from_segment_id VARCHAR2(40),
to_segment_id VARCHAR2(40),
connection_airport VARCHAR2(3),
scheduled_buffer_minutes NUMBER,
projected_buffer_minutes NUMBER,
required_buffer_minutes NUMBER
);
That edge table carries the central business fact in the tutorial: how much connection time the traveler is projected to have and how much the tutorial rule requires. By putting those values on an edge, the graph path can explain the connection risk as a relationship, not only as a standalone row.
Expected output:
Dropped old demo objects: OK
Created tables: 11
policy_chunks.embedding data type: VECTOR
Schema creation: OK
Step 3: Load staged airport and flight data
Now load the staged airport and flight CSVs. The airport file uses a small subset shaped after OurAirports fields. The flight file uses a compact sample shaped after BTS on-time performance fields.
python 02_load_airports.py
python 03_load_flights.py
The flight load script filters unusable records, stores scheduled and actual timing fields, and computes route-level summary values. The route risk score is deliberately simple: it combines p90 arrival delay, cancellation rate, and diversion rate into an inspectable ranking feature.
The route summary logic is intentionally visible in Python rather than hidden behind a stored procedure:
fromstatisticsimportmedian
for(origin,dest),rowsingrouped.items():
# Each group becomes one route summary, such as JFK->ORD or ORD->SFO.
# Keep the score inspectable: delay risk plus cancellation/diversion penalties.
risk=(
common.p90(delays)
+100*(cancelled/len(rows))
+100*(diverted/len(rows))
)
# This tuple becomes one row in route_summaries and one graph edge.
route_tuple=(
f"{origin}_{dest}",
origin,
dest,
len(rows),
median(scheduled),
median(actual),
sum(dep_delays)/len(dep_delays),
sum(delays)/len(delays),
common.p90(delays),
cancelled/len(rows),
diverted/len(rows),
float(rows[0]["Distance"]),
risk,
)
The route summary also stores median scheduled elapsed time, median actual elapsed time, average departure delay, average arrival delay, p90 arrival delay, cancellation rate, diversion rate, distance, and the tutorial risk score. That score is not a prediction model. It is a transparent ranking feature that lets the demo compare route evidence without hiding the math.
The percentile helper is intentionally easy to inspect:
This step creates the passenger itinerary, the delayed inbound segment, the outbound connection, candidate route alternatives, and fictional policy chunks.
python 04_build_demo_context.py
The policy documents are tutorial data, not airline policy. They cover same-carrier rebooking, missed connections, baggage transfer, demo minimum connection time, and explanation boundaries.
This script is where the connected use case becomes visible. It creates:
ITIN-100, the synthetic passenger itinerary.
SEG-1, the delayed JFK to ORD inbound segment.
SEG-2, the ORD to SFO outbound segment at risk.
A segment_connect_edges row that says SEG-1 connects to SEG-2 at ORD.
A segment_alternative_route_edges row that points from SEG-2 to DEN as the ranked alternative.
This row does two jobs. First, it connects the at-risk outbound segment to the Denver alternative in the graph. Second, it stores the explanation text and computed candidate score that the final answer can summarize. The fixture has one tutorial alternative, so it receives rank 1; the score still comes from route summaries instead of a hard-coded constant. That is the GraphRAG pattern in miniature: the LLM should not invent the reroute. It should summarize retrieved evidence.
Finally, the script stages fictional policy chunks:
We insert the chunks before embedding them because the database row is the unit of retrieval. Step 6 fills the vector column, but the row already contains the title, text, and source note that the answer can cite.
Expected output:
Route summaries loaded: <route_summary_count>
Projected ORD buffer: 22
Policy chunks staged: 5
Demo context build: OK
Step 5: Create the SQL property graph
Create the graph after the vertex and edge tables are populated:
python 05_create_property_graph.py
The graph uses airports, itineraries, and itinerary segments as vertices. Route summaries and flight instances become airport-to-airport edges. Helper tables represent itinerary structure and route alternatives.
The complete graph DDL in the demo package includes route, flight, itinerary-to-segment, segment-to-segment, segment-origin, segment-destination, and segment-alternative edge tables. The shortened snippet above shows the modeling pattern.
The graph query asks for a path, not just a row lookup:
SELECT*
FROM GRAPH_TABLE(travel_disruption_graph
MATCH
(seg IS segment)-[origin_edge IS departs_from]->(origin IS airport)
-[first_leg IS has_route_to]->(mid IS airport)
-[second_leg IS has_route_to]->(dest IS airport),
(seg)-[alt IS has_alternative_route]->(mid)
WHERE seg.segment_id ='SEG-2'
AND origin.airport_code ='ORD'
AND mid.airport_code ='DEN'
AND dest.airport_code ='SFO'
COLUMNS (
seg.segment_id AS disrupted_segment_id,
origin.airport_code AS origin_airport,
mid.airport_code AS alternative_connection_airport,
dest.airport_code AS destination_airport,
alt.candidate_rank AS candidate_rank,
alt.route_risk_score AS candidate_route_risk_score,
first_leg.route_risk_score AS first_leg_route_risk_score,
second_leg.route_risk_score AS second_leg_route_risk_score
)
);
Representative result:
disrupted_segment_id
origin_airport
alternative_connection_airport
destination_airport
candidate_rank
SEG-2
ORD
DEN
SFO
1
Before we move into vector retrieval, inspect the graph shape itself. The figure below uses circular vertices, labeled relationship pills, and connected edge property cards so the SQL graph definition is easier to connect to the query.
The route map earlier shows where the airports sit geographically. This model view shows what the database exposes to GRAPH_TABLE(): circular vertices are the things we traverse, relationship labels name the edges we follow, and the connected edge property cards show the evidence used to explain or rank the path.
Step 6: Embed policy chunks
Now generate policy embeddings with OpenAI and store them in policy_chunks.embedding.
python 06_embed_policy_chunks.py
The OpenAI provider wrapper keeps model calls out of the retrieval scripts. The retrieval scripts call a small interface instead of embedding provider code directly:
raiseRuntimeError("OpenAI returned an invalid embedding payload")
forvectorinvectors:
iflen(vector)!=self.settings.vector_dimension:
raiseRuntimeError("OpenAI embedding dimension does not match OPENAI_EMBEDDING_DIMENSION")
returnvectors
This keeps provider-specific code out of the retrieval path. The schema, graph query, and prompt builder only ask for embeddings or a generated answer. The dimension check is especially important because it catches a common vector bug before invalid rows are stored.
When the embedding script writes vectors, it converts Python floats into a database vector literal:
That helper makes the handoff visible: the OpenAI provider returns Python lists of floats, and Oracle receives a serialized vector representation that this tutorial passes through TO_VECTOR() for readability. Before adapting the pattern for production or large loads, verify the current python-oracledb vector binding guidance for your driver and database version; a target environment may prefer a driver-native vector binding path.
Oracle AI Database 26ai Free includes native vector support for this local lab, so no separate extension step is shown. We use VECTOR_DISTANCE() instead of shorthand vector distance operators such as <->, <=>, and <#> because the selected metric is visible in the SQL and easier for learners to inspect.
After embedding, a policy row has both readable text and a vector:
policy_key
title
content excerpt
embedding shape
connection_buffer
Connection buffer
Use a minimum domestic connection buffer of 40 minutes…
VECTOR(<embedding dimension>, FLOAT32)
same_carrier_rebook
Same-carrier rebooking
For missed connections caused by delay…
VECTOR(<embedding dimension>, FLOAT32)
The actual vector is a numeric array. The first few values are enough to show the shape:
The numbers are not meant to be read one by one. What matters is that the policy chunks and the question use the same OpenAI embedding model and dimension, so Oracle can compare them with VECTOR_DISTANCE().
The small learning dataset has only a few policy chunks and intentionally does not create a vector index. For larger datasets, evaluate HNSW neighbor-graph indexes and IVF or IVFFlat neighbor-partition indexes with the current Oracle AI Vector Search documentation, your embedding dimension, your latency goals, and your recall requirements.
Advanced
Step 7: Compare retrieval modes
Run the comparison script to see what each retrieval mode can and cannot explain:
python 07_compare_retrieval_modes.py
Plain policy RAG can retrieve missed-connection policy language, but it cannot calculate the connection window. Hybrid vector plus relational retrieval can calculate the window and expose route scores. GraphRAG adds the connected path that explains why one alternative is better.
The comparison script is the main teaching tool in the demo. It does not ask the LLM which mode is better. It retrieves evidence for each mode and prints the missing pieces so you can see why graph-aware retrieval changes the answer.
The plain RAG query is only vector search over policy text:
"ORDER BY VECTOR_DISTANCE(embedding, TO_VECTOR(:1), COSINE) "
"FETCH FIRST 2 ROWS ONLY",
[query_vector],
)
policy_rows=common.rows_to_dicts(cur)
The rows_to_dicts() helper turns cursor rows into dictionaries with lowercase column names. That makes later prompt construction explicit: the answer receives fields such as title, content, projected_buffer_minutes, and candidate_rank rather than anonymous tuple positions.
"WHERE segment_id = 'SEG-2' AND candidate_rank = 1"
)
alternative=common.rows_to_dicts(cur)[0]
This intermediate mode proves that ordinary relational retrieval already solves part of the problem. You do not need graph traversal to know that 22 minutes is less than 40. You need graph traversal when you want to explain how the at-risk segment, the candidate airport, and the route evidence connect.
Representative result:
projected_buffer_minutes
required_buffer_minutes
conclusion
22
40
connection is short by 18 minutes
Mode C adds the graph path, which is why it can cite the connected alternative instead of merely saying “look for a rebooking.”
The graph retrieval follows the edges created from the helper tables. It starts at the disrupted outbound segment, follows the segment origin edge to ORD, traverses route summaries from ORD to DEN and DEN to SFO, and also checks that the segment has a ranked alternative edge to DEN:
cur.execute(
"SELECT * FROM GRAPH_TABLE(travel_disruption_graph "
"MATCH (seg IS segment)-[origin_edge IS departs_from]->(origin IS airport) "
"-[first_leg IS has_route_to]->(mid IS airport) "
"-[second_leg IS has_route_to]->(dest IS airport), "
"(seg)-[alt IS has_alternative_route]->(mid) "
"WHERE seg.segment_id = 'SEG-2' "
"AND origin.airport_code = 'ORD' "
"AND mid.airport_code = 'DEN' "
"AND dest.airport_code = 'SFO' "
"COLUMNS ("
"seg.segment_id AS disrupted_segment, "
"origin.airport_code AS origin_airport, "
"mid.airport_code AS alternative_connection_airport, "
"dest.airport_code AS destination_airport, "
"alt.candidate_rank AS candidate_rank, "
"alt.route_risk_score AS candidate_route_risk_score, "
"first_leg.route_risk_score AS first_leg_route_risk_score, "
"second_leg.route_risk_score AS second_leg_route_risk_score"
")) ORDER BY candidate_rank"
)
alternative_path=common.rows_to_dicts(cur)
This is where the demo moves from “retrieve some rows” to “retrieve a connected explanation.” The graph path proves SEG-2 -> ORD -> DEN -> SFO, while the alternative edge proves that DEN is the ranked candidate midpoint for the disrupted segment. The edge properties carry rank and route scores, so the answer summarizes retrieved evidence instead of inventing a reroute.
This router is intentionally basic. Its purpose is to show the retrieval design decision, not to solve natural-language routing. Policy questions can use vector retrieval. Questions about connection risk, alternatives, route paths, or itinerary structure need graph evidence. A production implementation might replace this with a tested classifier, but the principle is the same: choose retrieval tools based on the evidence needed to answer safely.
Step 8: Generate the grounded answer
Finally, generate the passenger-facing answer from Mode C evidence:
python 08_answer_question.py
Representative answer:
You are unlikely to make the current connection. The projected arrival at ORD leaves less than the demo 40-minute connection buffer before the ORD to SFO departure. The ranked tutorial alternative is ORD to DEN to SFO because the demo graph connects the at-risk segment to DEN and the candidate score is computed from the staged route summaries.
The answer includes an explanation path:
Passenger itinerary
-> inbound segment JFK to ORD
-> projected arrival delay
-> connection at ORD
-> required connection buffer
-> outbound segment ORD to SFO
-> alternative route ORD to DEN to SFO
-> policy chunk: same-carrier rebooking
The answer script builds the prompt from retrieved evidence, not from the user’s question alone:
prompt=f"""Answer with grounded travel disruption guidance only.
Use these headings exactly: Recommendation, Connection feasibility, Evidence path,
Policy basis, Alternatives considered, Confidence and caveat, Data freshness disclaimer.
Use only supplied graph facts, relational facts, and policy chunks. If evidence is missing,
State that this is tutorial data, not real-time operational airline advice.
"""
answer=provider.generate(prompt)
The headings force the generated answer to separate recommendation, feasibility, evidence, policy basis, alternatives, confidence, and data freshness so reviewers can spot unsupported advice.
The generation method uses the same narrow OpenAI wrapper as embeddings:
raiseRuntimeError("OpenAI returned an empty generation result")
returntext.strip()
That keeps the tutorial focused on GraphRAG rather than provider plumbing. The rest of the code only knows that the provider can embed text and generate grounded text.
Run the static validator and optional cleanup when finished:
python 09_validate_demo.py
python 10_cleanup_demo.py
The validator checks file presence, syntax, credential hygiene, local Compose setup, init SQL, and static project consistency. Live database execution uses the included Oracle AI Database 26ai Free container plus your OpenAI configuration.
Tips And Troubleshooting
Keep the tutorial schema small while learning the pattern. It is easier to inspect a six-airport graph than to debug a full operational feed before the retrieval modes are clear.
Use environment variables for all credentials and model identifiers. The demo package’s .env.example is intentionally placeholder-only, and the scripts should never print passwords, tokens, wallet contents, or private endpoint values.
When graph creation fails, check that the helper edge tables are populated and that the source and destination keys reference the intended vertex tables. The tutorial graph deliberately avoids using the same relational table as both a vertex table and an edge table in the same relationship.
When vector results look surprising, inspect the retrieved doc_name, chunk_title, and distance values before changing prompts. For a larger policy corpus, add indexing only after validating the embedding model, vector dimension, metric, and expected recall behavior.
For production services, create a python-oracledb connection pool with oracledb.create_pool() instead of opening one connection per question. Batch embedding calls where your OpenAI rate limits and latency goals support batching, and monitor cost, rate limits, and latency before scaling bulk loads or query fan-out.
Telemetry is optional for this tutorial run. If your environment emits spans to shared infrastructure, keep attributes free of secrets and treat delivery confirmation as operational evidence rather than a prerequisite for understanding the GraphRAG pattern.
Oracle AI Vector Search Notes
This tutorial uses the included Oracle AI Database 26ai Free Compose setup for local execution. The mounted init SQL creates a least-privilege graphrag_demo user in FREEPDB1; the Python checkpoints then create only application-owned tutorial objects.
Oracle AI Database 26ai-compatible environments include native support for the VECTOR data type and VECTOR_DISTANCE(). If you adapt the demo to another environment, keep the runtime user least-privilege and verify the vector and SQL property graph features before running the checkpoints.
The demo uses small deterministic vectors so every ranking step is inspectable. In production, keep vector generation provider-configurable: use the approved embedding provider or embedding API for the environment, and generate document vectors and query vectors with the same embedding model so their vector dimensions and distance relationships are comparable.
Metric choice depends on the embedding model and scoring goal: cosine is useful when vector direction matters more than magnitude, Euclidean is useful when absolute distance and vector magnitude are meaningful, and dot-product-style scores are useful only when the model and normalization strategy make score direction explicit.
For larger datasets, evaluate vector index choices in the target environment. HNSW indexes are a good fit when recall and low-latency nearest-neighbor lookups matter and additional memory is acceptable. IVF or IVFFlat-style neighbor partition indexes are useful when partitioned search and memory control are more important. The right choice depends on workload size, latency goals, recall goals, and metric alignment.
This tutorial keeps the runnable lab focused on the small policy_chunks table and does not publish exact vector-index DDL. Before adding an index example to production documentation, validate the current Oracle AI Vector Search syntax in the target environment and use table names from the real schema being documented.
Conclusion
We built a travel disruption assistant that shows why GraphRAG matters for connected questions. Plain policy retrieval finds relevant words, hybrid retrieval adds structured facts, and the graph-aware mode supplies the path that ties the passenger, flights, airports, connection buffer, route alternatives, and policy evidence together.
This pattern fits applications where the answer depends on both semantic text and explainable relationships. It is not a substitute for validated operational systems, live airline data, or production decision policies. The next useful step is to run the extracted local demo, inspect the Mode A/B/C evidence side by side, and then adapt the schema to one additional connected scenario.
Related resources:
Oracle AI Database – Start with the database platform used for the relational, vector, and graph portions of the lab.
]]>https://redstack.dev/2026/06/15/how-to-build-a-graphrag-travel-assistant-with-oracle-ai-database-26ai/feed/04686From GraphRAG Demo to Enterprise AI System with Oracle AI Database 26ai
https://redstack.dev/2026/06/12/from-graphrag-demo-to-enterprise-ai-system-with-oracle-ai-database-26ai/
https://redstack.dev/2026/06/12/from-graphrag-demo-to-enterprise-ai-system-with-oracle-ai-database-26ai/#respondFri, 12 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4671Continue reading →]]>Key Takeaways
GraphRAG helps when enterprise answers depend on relationships, not just similar text. A passage can mention the right product or policy and still be wrong for the customer, asset, contract, region, date, entitlement, or user.
Start with a minimum viable knowledge graph. Model the smallest set of entities, relationships, and linked sources that improves one real retrieval workflow before expanding into a broader enterprise graph.
Oracle AI Database 26ai can support a database-centered GraphRAG pattern. SQL property graphs, Oracle AI Vector Search, relational tables, JSON metadata, and SQL predicates can work together while the application or retrieval service orchestrates the workflow.
The useful output is an evidence bundle. A practical GraphRAG system should return passages, graph paths, structured facts, source identifiers, provenance, and authorization-filtered context that an AI application can use safely.
A useful AI answer needs more than similar text
A support engineer asks what sounds like a straightforward question:
Which maintenance policy applies to ACME’s pump 17 after the seal failure?
A vector search workflow may get close. It might retrieve a product manual for Pump X9, a support note about seal failure, a policy document about pump maintenance, and a contract clause that mentions replacement work.
That is a good start. It is not yet a good answer.
The policy may mention the right product but apply only in another region. The support note may describe the right failure mode but be tied to a retired product version. The contract clause may use similar language but belong to another customer. A retrieved passage can be semantically relevant and still be wrong for this customer, this asset, this contract, this entitlement, this incident date, or this user.
That is the practical gap GraphRAG is meant to close.
GraphRAG is a retrieval-augmented generation pattern that adds graph-based relationship context to semantic retrieval. Instead of sending only similar passages to a model, a GraphRAG system can also retrieve connected entities, relationship paths, structured facts, source identifiers, and provenance.
In this article, Oracle GraphRAG means a GraphRAG-style architecture pattern built with Oracle AI Database 26ai capabilities. It is not a separate product name. The examples use Oracle AI Database 26ai capabilities such as SQL property graphs and Oracle AI Vector Search.
The practical pattern is simple: use vector search to find candidate text, use graph traversal to understand which entities and relationships matter, use SQL predicates to apply structured filters and authorization, and send the AI workflow an evidence bundle rather than a loose pile of similar passages.
For the ACME question, the retrieval layer should be able to answer questions like these before it sends context to a model:
Does ACME Manufacturing own PUMP-17?
Which product is PUMP-17 an instance of?
Which contract is active for ACME?
Which entitlement does that contract grant?
Does the entitlement cover Pump X9?
Which policy governs Pump X9 in EMEA on the incident date?
Which support document cites the policy?
Is the requesting user allowed to see this contract, policy, asset, and document context?
That is the shift. We are not just looking for text about seal failure. We are looking for evidence that applies.
Where this article fits in the graph series
This article builds on a few recent RedStack posts about graph features in Oracle AI Database 26ai. If you want the hands-on starting point, begin with Build your first SQL property graph in Oracle AI Database 26ai. That post shows the basic shape of creating and querying a graph.
The ACME/PUMP-17 example below is a fictional product-support scenario used to illustrate the architecture pattern.
Why vector similarity is not always applicable evidence
Vector search is valuable because language is messy. Users rarely ask questions using the exact words in your documents. A support engineer may ask about “pump 17,” while the manual says “Pump X9 installed asset,” the policy says “sealed pump assembly,” and the case note says “mechanical seal failure.”
Oracle AI Vector Search helps with that semantic gap. It lets applications store vector embeddings with business data and query for semantic similarity. That is a strong starting point for retrieval-augmented generation.
The hard part begins when similar text has to be tested against business context. Similarity helps find candidate evidence. It does not prove that the evidence applies.
For our support example, a policy passage may be highly similar to the question. It may mention Pump X9 and seal failure. But the answer can still be wrong if ACME does not have the right entitlement, the contract is inactive, the policy applies only outside EMEA, the policy was not effective on the incident date, or the user cannot access the contract details.
That is why the retrieval path needs relationships among customers, assets, products, contracts, entitlements, policies, regions, dates, support documents, and incidents.
Those relationships are often already present in operational systems. They appear as foreign keys, relationship tables, status columns, date ranges, document metadata, entitlement rules, and access predicates. A knowledge graph becomes useful when it makes those relationships retrievable for the AI workflow.
A knowledge graph represents important business entities and the relationships among them. In enterprise AI, that graph might connect customers to contracts, assets to products, policies to regions, suppliers to components, employees to certifications, or incidents to affected services.
The graph is not valuable because it is abstract. It is valuable because the relationships change which evidence should be retrieved, how the answer should be explained, or what the workflow should do next.
There is a boundary worth stating plainly. Graph context supports retrieval and explanation. It does not replace business rules, data quality work, authorization, review workflows, or application-level evaluation. If a policy decision requires approval, the graph should help assemble evidence for that decision. It should not pretend to be the decision-maker.
The same pattern shows up outside product support. In supplier risk, the answer may depend on suppliers, facilities, contracts, certifications, incidents, components, and affected products. In policy compliance, it may depend on regulations, controls, policies, exceptions, evidence documents, and business units. In workforce planning, it may depend on employees, roles, certifications, projects, skills, and learning material.
Graph-enriched retrieval is useful when relationships change which evidence is applicable, how the answer is explained, or what action the workflow should take next.
What is a minimum viable knowledge graph?
A minimum viable knowledge graph is the smallest set of entities, relationships, and linked sources that improves one real AI retrieval workflow. It is not an enterprise-wide ontology. It starts with one use case, one domain, and the relationships that change whether an answer is correct, applicable, or explainable.
That definition matters because graph projects are easy to overbuild. Once you start drawing entities and relationships, everything feels connected to everything else. Customers connect to accounts, accounts connect to contracts, contracts connect to products, products connect to suppliers, suppliers connect to facilities, facilities connect to shipments, and suddenly your “first graph” has become a long-running modeling program.
Start smaller.
The first graph should earn the right to grow. Start with the path that makes one answer better.
For the support scenario, the first graph might contain customer, asset, product, contract, entitlement, policy, and support document entities. The first relationships might be just as small: customer owns asset, asset is an instance of product, customer has contract, contract grants entitlement, entitlement covers product, policy governs product, and support document cites policy.
That is enough to test whether a policy applies to a customer asset. It is also small enough for a development team to reason about.
Figure 2. A minimum viable knowledge graph starts with the relationships that change answer quality for one use case.
The practical test for each relationship is simple:
Would this relationship change which evidence we retrieve, how we rank it, or how we explain the answer?
If the answer is no, it can probably wait.
A good first graph has one domain, one AI use case, a small set of entity types, a small set of relationship types, a few trusted documents or records, a measurable retrieval question, and a way to compare results against known answers.
Product support is a good starter domain because support questions often depend on customer assets, product versions, contracts, entitlements, policies, and support documents. Policy compliance, supplier risk, asset maintenance, customer service, and workforce skills can also work well.
The point is not to avoid ambition. The point is to make progress. You can add suppliers, facilities, incidents, exceptions, regulatory controls, service history, and case outcomes later. Add them when a real retrieval failure shows that the graph is missing something.
How Oracle AI Database 26ai capabilities map to GraphRAG
Oracle AI Database 26ai can support this pattern because graph, vector, relational, JSON, and SQL capabilities can be used together in a database-centered architecture. That does not mean the database automatically builds the GraphRAG application. It means developers have a practical foundation for keeping retrieval close to the business data that gives evidence its meaning.
A SQL property graph exposes selected database objects as vertices and edges with labels and properties, so applications can query relationship patterns while still working inside a SQL-centered database architecture. In Oracle AI Database 26ai, CREATE PROPERTY GRAPH defines a property graph over supported database objects, and GRAPH_TABLE can match graph patterns and project results as rows and columns.
For the support workflow, the graph can expose customers, assets, products, contracts, entitlements, policies, support documents, and incidents. The graph query retrieves the path that explains applicability: ACME owns PUMP-17; PUMP-17 is an instance of Pump X9; ACME has an active contract; the contract grants Premium maintenance; Premium maintenance covers Pump X9; and the policy governs Pump X9 in EMEA on the incident date.
Oracle AI Vector Search does a different job. It provides vector storage and similarity search capabilities in Oracle AI Database 26ai, allowing applications to retrieve semantically similar passages, documents, notes, or entity summaries where embeddings have been stored and indexed for retrieval. In this workflow, vector search might retrieve policy chunks, support document chunks, product manual excerpts, case notes, contract clause summaries, or entity summaries about seal failure.
Relational tables remain central. They hold operational facts such as customer records, contract status, asset inventory, product versions, policy effective dates, tenancy, and approval state. SQL is the control plane for applicability: region, date, status, tenant scope, product lifecycle state, data classification, user access predicates, and business rules.
JSON is useful where flexible metadata helps. A document chunk may carry JSON metadata for page number, section title, source system, extraction confidence, classifier output, or retrieval trace. An application may serialize an evidence bundle as JSON before sending it to an LLM or another service. Oracle AI Database 26ai supports JSON data management alongside relational data, which is useful when metadata changes faster than the core operational schema.
Security has to travel with the retrieval path. If the user cannot access a contract, policy, support case, document chunk, graph path, or structured fact, that item should stay out of retrieval results, evidence bundles, prompts, logs, traces, and responses.
Database-layer controls such as privileges and row-level predicates can help, and the Oracle AI Database Security Guide covers the broader database security model. The application still has to pass user context, call the right retrieval service, apply authorization-aware predicates, and avoid leaking restricted context into prompts, logs, traces, or responses.
The architecture boundary is important. Oracle AI Database 26ai provides the graph, vector, relational, JSON, and SQL foundation. The application or retrieval service orchestrates entity resolution, embedding calls or lookup, graph traversal, result fusion, prompt assembly, response handling, evaluation, and workflow-specific approval logic.
A practical Oracle GraphRAG flow
A practical Oracle GraphRAG flow turns a user question into an evidence bundle. The retrieval service does the orchestration, while Oracle AI Database 26ai capabilities provide graph, vector, relational, JSON, and SQL context for the bundle.
Figure 1. The application or retrieval service orchestrates the GraphRAG flow. Oracle AI Database 26ai supplies graph, vector, relational, JSON, and SQL capabilities used to assemble the evidence bundle.
In a typical flow:
The application captures the user question, identity, tenant or customer context, and any known entities from the UI.
The application embeds or interprets the question.
Oracle AI Vector Search retrieves candidate passages, chunks, records, or summaries.
The application resolves relevant entities such as customer, asset, product, policy, contract, incident, or region.
A SQL property graph query traverses relationships among those entities.
SQL predicates apply region, date, status, entitlement, tenant, data classification, and authorization-aware filters.
The retrieval service assembles an evidence bundle with passages, graph paths, structured facts, source identifiers, and provenance.
The evidence bundle is sent to an LLM, assistant, search workflow, recommendation service, decision-support UI, or bounded agent.
The application returns an answer, recommendation, or next action with source references and workflow controls.
An evidence bundle is the context assembled for an AI workflow. It gives an LLM, assistant, search application, recommendation service, decision-support workflow, or agent a grounded basis for an answer or next action.
That “grounded basis” wording is intentional. The evidence bundle is not a guarantee that the generated answer is correct. It is a better input to the workflow. The application still needs evaluation, response controls, user experience design, and human review where the domain requires it.
Walkthrough: policy context for a customer asset
Let’s make the pattern concrete with a small fictional product-support slice. This is a walkthrough, not a full copy-paste tutorial. The important part is the retrieval shape: the graph retrieves the applicability path, while vector search retrieves semantically relevant passages that the application can filter against that path.
Here is the data slice:
Customer: ACME Manufacturing
Customer key: acme-mfg
Policy-applicability region: EMEA
Asset: PUMP-17
Product: Pump X9
Contract: ACME-2026-PLATINUM
Contract status: ACTIVE
Entitlement: Premium maintenance
Policy: Pump X9 Seal Failure Policy
Policy code: pump-x9-seal-failure-emea
Incident type: seal_failure
Support doc: Pump X9 Maintenance Guide
Document code: pump-x9-maint-guide
Event date: 2026-03-14
A vector search for the engineer’s question may retrieve passages about pump seals, maintenance procedures, and policy language. The graph’s job is narrower. It should retrieve the path that proves which policy is applicable to this customer asset.
In plain text, the useful path looks like this:
ACME Manufacturing
owns PUMP-17
is an instance of Pump X9
ACME Manufacturing
has ACME-2026-PLATINUM
grants Premium maintenance
covers Pump X9
Pump X9
is governed by Pump X9 Seal Failure Policy
applies in EMEA
applies to seal_failure
is cited by Pump X9 Maintenance Guide
A SQL property graph query can make that path retrievable once the underlying graph, labels, edge definitions, properties, and predicates are defined.
For this simplified walkthrough, the customer’s region is the policy-applicability region. In a production support system, that predicate might use the asset install site, service territory, contract region, or incident location instead.
The following block is SQL/PGQ-style pseudocode, not a complete runnable script. It is meant to show the relationships and predicates that belong in the retrieval path. A runnable version would require tested table definitions, sample data, privileges, a CREATE PROPERTY GRAPH statement, and target-environment syntax.
The authorization checks are intentionally shown as architecture requirements rather than runnable SQL. Do not send a graph path, document chunk, or structured fact to the model unless the requesting user is allowed to see it.
A conceptual result from that traversal would identify:
Customer: ACME Manufacturing
Asset:PUMP-17
Product: Pump X9
Contract:ACME-2026-PLATINUM
Entitlement: Premium maintenance
Policy: Pump X9 Seal Failure Policy
Policy code:pump-x9-seal-failure-emea
Policy region: EMEA
Effective from: 2026-01-01
Source document: Pump X9 Maintenance Guide
Source code:pump-x9-maint-guide
This result gives the AI workflow something more useful than a similar passage. It gives the path that explains applicability:
Pump X9 Seal Failure Policy applies to ACME Manufacturing's PUMP-17
because ACME owns the asset, the asset is an instance of Pump X9,
ACME has an active premium maintenance contract, the entitlement covers
Pump X9, the policy governs Pump X9 in EMEA for seal failure, and the
maintenance guide cites the policy.
Now vector search can plug in cleanly. Oracle AI Vector Search can retrieve passages about seal failure from policy chunks, support documents, or product manuals where those passages have embeddings available. The graph traversal identifies which policies and products apply to this customer asset. SQL predicates then keep only passages that match the applicable policy, incident type, region, effective date, entitlement, tenant scope, and authorization rules.
Vector search is still doing important work. The graph does not replace semantic retrieval; it helps decide which semantically relevant passages are applicable to this business situation.
The evidence bundle might look like this at the application boundary:
{
"question":"Which maintenance policy applies to ACME's pump 17 after the seal failure?",
"reason":"The support document cites the applicable policy."
}
],
"passages":[
{
"source_code":"pump-x9-maint-guide",
"policy_code":"pump-x9-seal-failure-emea",
"title":"Pump X9 Maintenance Guide",
"section":"Seal failure procedure"
}
],
"structured_facts":{
"contract_status":"ACTIVE",
"policy_effective_from":"2026-01-01",
"incident_type":"seal_failure",
"event_date":"2026-03-14"
},
"provenance":[
{
"source_code":"pump-x9-maint-guide",
"source_type":"support_document",
"title":"Pump X9 Maintenance Guide"
},
{
"source_code":"pump-x9-seal-failure-emea",
"source_type":"policy",
"title":"Pump X9 Seal Failure Policy"
}
]
}
This JSON is not a built-in database response. It is an application pattern. The retrieval service decides how to assemble, filter, log, and pass this context to the next consumer.
The access_context field is illustrative. The important point is that authorization filtering happens before the bundle is logged, sent to a model, or returned to a caller.
The walkthrough proves a modest but useful point: a small graph path can retrieve applicability context. It does not build a full LLM app, implement production authorization, solve entity resolution, or evaluate generated answers. That is fine. The first step is to make the relationship retrievable.
Turn graph-enriched retrieval into a knowledge service
The useful boundary is not “the graph.” The useful boundary is a service that returns trusted context for a workflow.
If we bury the graph query inside one chatbot, the pattern will not travel very far. The next search app, agent, recommendation service, or case-management screen will rebuild the same logic. A better design is to expose graph-enriched retrieval as an application knowledge service.
A platform team might expose a bounded service shape like this:
Behind that boundary, the implementation could use SQL lookups, GRAPH_TABLE, Oracle AI Vector Search, JSON metadata, relational filters, and authorization-aware predicates. The caller should not need to know the graph schema or the vector indexing strategy.
A conceptual request might look like this:
{
"customer_key":"acme-mfg",
"asset_tag":"PUMP-17",
"incident_type":"seal_failure",
"event_date":"2026-03-14"
}
And a conceptual response could return the applicable policy, the relationship paths, and the source references:
{
"applicable_policy":{
"policy_code":"pump-x9-seal-failure-emea",
"title":"Pump X9 Seal Failure Policy",
"region":"EMEA",
"incident_type":"seal_failure",
"effective_from":"2026-01-01"
},
"relationship_paths":[
"ACME Manufacturing owns PUMP-17",
"PUMP-17 is an instance of Pump X9",
"ACME Manufacturing has active contract ACME-2026-PLATINUM",
"ACME-2026-PLATINUM grants Premium maintenance",
"Premium maintenance covers Pump X9",
"Pump X9 Seal Failure Policy governs Pump X9 in EMEA for seal failure",
"Pump X9 Maintenance Guide cites Pump X9 Seal Failure Policy"
],
"sources":[
{
"source_code":"pump-x9-maint-guide",
"title":"Pump X9 Maintenance Guide",
"section":"Seal failure procedure"
}
]
}
The service contract is conceptual. It is not a built-in Oracle endpoint; it is an application boundary that hides graph schema, vector indexing strategy, and authorization logic from callers.
Figure 3. Once the first graph path is useful, expose graph-enriched retrieval as reusable services instead of rebuilding context assembly in every application.
The service layer can start small. Entity lookup resolves user terms to trusted database entities. Relationship traversal returns paths connecting customers, assets, products, contracts, policies, and documents. Policy-context retrieval returns policies applicable to a customer, asset, product, region, date, or incident. Provenance lookup returns source documents, sections, codes, and lineage. Context assembly builds evidence bundles for questions.
An agent retrieval tool is another useful boundary. It gives an agent bounded access to context without giving it raw enterprise data access.
This is where a GraphRAG demo starts to look like a system. The graph is still small, but the boundary is reusable.
Where GraphRAG helps in enterprise AI workflows
Graph-enriched retrieval helps when relationships change which evidence is applicable, how the answer is explained, or what action the workflow should take next.
For semantic search and question answering, a support assistant can retrieve passages about a product failure, then use graph context to check the customer’s asset, contract, entitlement, product, and region. The workflow can return source-backed evidence for the applicable policy instead of a generic policy summary.
For knowledge discovery, a product team can ask which policies, support cases, and incidents are connected to a recurring asset failure. Vector retrieval may find relevant notes. Graph traversal can connect those notes to products, assets, policies, regions, and affected customers.
For recommendations, a service workflow can recommend the next troubleshooting step based on product, asset history, known failure modes, entitlement, and trusted support documents. The recommendation is more useful when the system can explain the path that led to it.
For decision support, a case manager can see why a policy applies before approving an exception. The evidence bundle can show the applicable contract, entitlement, policy, support document, event date, and source references. That does not remove the need for review. It makes the review easier.
For AI agents, the pattern is especially important. An agent should have bounded retrieval tools instead of open-ended access to raw enterprise tables. Give the agent a tool that returns policy context, graph paths, source passages, and provenance. Let the application decide what actions are allowed, what needs approval, and what gets logged.
This pattern is not necessary for every AI system. If a workflow only needs to find a few public documents, vector or hybrid search may be enough. Use GraphRAG when relationship context materially changes retrieval quality or workflow behavior.
What to build next
The next step is not to schedule a six-month ontology program. The next step is to pick one useful workflow and make one relationship path retrievable.
Start with a sequence like this:
Pick one domain, such as product support, policy compliance, supplier risk, asset maintenance, customer service, or workforce skills.
Pick one AI use case where users already ask questions today.
Write five real questions users ask in that workflow.
Identify the relationships that change the answer.
Model the smallest useful set of entities and edges.
Link trusted documents or chunks to graph entities.
Add vector search where semantic retrieval improves the workflow.
Use SQL predicates for status, date, region, tenant, entitlement, and authorization.
Evaluate against known questions and expected evidence.
Expand only when failures show a missing entity, relationship, source, or filter.
The first evaluation should be practical. Did the system retrieve the right source passages? Did it find the right graph path? Did it apply the right region, date, status, entitlement, tenant, and authorization filters? Did it avoid restricted records? Did it return source references that a human can inspect?
You can also compare the graph-enriched result with a vector-only result. The question is not whether the graph feels more sophisticated. The question is whether it retrieves better evidence for the workflow.
If the system fails because the customer-to-asset relationship is missing, add it. If it fails because policy effective dates are not modeled, add them. If it fails because support documents are not linked to products or policies, add that link. Let failures guide the graph’s growth.
That keeps the graph honest. It grows because it improves retrieval, explanation, recommendation, or decision support.
Conclusion
GraphRAG becomes useful when relationships become retrievable evidence. Similar passages matter, but enterprise AI often needs more: customer context, asset ownership, product identity, active contracts, entitlements, policy scope, region, effective dates, permissions, source references, and provenance.
Oracle AI Database 26ai is a practical foundation for this pattern because SQL property graphs, Oracle AI Vector Search, relational data, JSON metadata, and SQL predicates can work together in a database-centered architecture. The application still orchestrates the workflow, but the retrieval layer can stay close to the governed business data that gives evidence its meaning.
The first project should be small. Build a minimum viable knowledge graph for one workflow. Use vector search to find candidate passages. Use graph traversal and SQL predicates to test applicability. Assemble an evidence bundle that an LLM, assistant, search app, recommendation service, decision-support workflow, or bounded agent can use.
Pick one workflow, find the relationship that changes the answer, and build the smallest graph path that makes that relationship retrievable.
]]>https://redstack.dev/2026/06/12/from-graphrag-demo-to-enterprise-ai-system-with-oracle-ai-database-26ai/feed/04671Oracle Connection Pooling in Spring Boot: When to Use HikariCP and When to Use UCP
https://redstack.dev/2026/06/11/oracle-connection-pooling-in-spring-boot-when-to-use-hikaricp-and-when-to-use-ucp/
https://redstack.dev/2026/06/11/oracle-connection-pooling-in-spring-boot-when-to-use-hikaricp-and-when-to-use-ucp/#respondThu, 11 Jun 2026 13:22:50 +0000https://redstack.dev/?p=4655Continue reading →]]>Key Takeaways
Choose HikariCP when your requirement is standard Spring Boot JDBC pooling. HikariCP is a strong, widely used choice because Spring Boot auto-configuration supports it directly and exposes HikariCP settings under spring.datasource.hikari.*.
Choose Oracle Universal Connection Pool when Oracle-specific connection management matters. UCP is the better fit when the application’s production contract includes Oracle Database high availability-related behavior, service-aware connection management, Fast Application Notification, Fast Connection Failover, or runtime load-balancing behavior in a supported configuration.
Choose by operational fit, not generic speed claims. HikariCP and UCP solve overlapping but not identical problems, and a pool that behaves well for one workload may behave differently under bursty requests, longer transactions, retrieval workloads, or background jobs.
Test with the workload shape your users will actually hit. A local lab that runs the same Spring Boot application with two pool profiles helps you observe saturation, timeout behavior, and connection pressure before production.
Why Connection Pooling Becomes a Production Problem
A Spring Boot application can look perfectly healthy on your laptop and still run into trouble as soon as real traffic arrives.
At first, the symptoms are easy to misread. A few requests get slower. Then some requests fail with connection timeout errors. Then the database team asks why one service is trying to open more sessions than anyone expected.
AI application patterns can make this show up sooner because a single user request may perform several database operations: retrieval, metadata reads, vector search, chat-memory writes, usage updates, or audit inserts. From the outside, that is still one request. Inside the application, it may touch Oracle Database several times.
The connection pool is where that work becomes visible.
In a Spring Boot application, the connection pool controls how concurrent application work becomes Oracle Database connection and session demand. HikariCP and Oracle Universal Connection Pool (UCP) are both good choices for Oracle-backed Spring Boot applications. HikariCP fits teams that want standard Spring Boot JDBC pooling: connection reuse, explicit pool limits, and clear timeout behavior. UCP fits teams that want Oracle-optimized connection management, especially when high availability-related integration is part of the requirement.
Version basis: the examples below assume Linux and Bash, JDK 21 or newer, a supported Spring Boot line, Oracle Database Free started with Docker Compose, and k6 installed on the Docker host for the local load harness. Use the Oracle Spring Boot Starter for UCP version that matches your Spring Boot line.
The practical answer is simple: choose HikariCP when you want straightforward Spring Boot JDBC pooling and your platform is built around the Spring Boot default pool; choose Oracle UCP when Oracle-specific connection management, service-aware behavior, or high availability-related requirements matter; and test with your workload shape instead of choosing from generic speed claims.
Let’s make that concrete.
What a Connection Pool Does in a Spring Boot Oracle Application
A connection pool keeps a controlled set of physical database connections available for application code. Instead of opening a new database connection for every request, the application borrows a connection from the pool, uses it, and returns it.
The main terms are worth being precise about.
A physical connection is the actual JDBC connection from the application process to Oracle Database. In many common configurations, that connection corresponds to a database session.
A database session is the server-side Oracle Database state associated with a connected client. Pool sizing matters because too many application connections can create too much database session demand.
A borrowed connection is a connection currently checked out by application code.
A returned connection is back in the pool and available for another request.
The maximum pool size is the upper bound on how many connections from that pool can exist at the same time, including borrowed and idle connections.
The minimum idle or minimum pool size setting controls how many connections the pool tries to keep ready for use, depending on the pool implementation.
A connection timeout or borrow wait timeout controls how long a request waits when every connection is busy.
Pool saturation happens when all available connections are borrowed and new requests must wait.
Connection validation is how the pool checks whether a connection is still usable before giving it to application code.
That is the mechanical view. The design view is more important:
The connection pool is where application concurrency becomes database connection and session demand.
A connection pool turns concurrent application work into a controlled number of Oracle Database connections and, in common configurations, sessions. When all pool connections are borrowed, later requests wait or time out.
Here is the quick arithmetic every team should do before production:
4 application instances × maximum pool size 5 = up to 20 database connections
That does not mean the service supports only five users per instance. It means one application instance can hold up to five database connections at the same time. If you run four replicas, that setting can become up to 20 database connections from this one service before you count other applications, background jobs, administration sessions, or monitoring.
This is an upper-bound conversation starter, not a complete capacity formula. It is still useful because it makes the hidden multiplier visible.
A larger pool may reduce waiting in a local test, but it can also increase database session pressure. A smaller pool may protect the database, but it can also create unnecessary request wait time and timeout errors.
The pool is a gate. It protects Oracle Database from unbounded application concurrency, and it becomes a visible bottleneck when the application asks for more concurrent database work than the pool allows.
HikariCP in a Spring Boot Oracle Application
HikariCP is a strong, well-supported choice in many Spring Boot JDBC applications because Spring Boot auto-configuration supports it directly. In a Spring Boot JDBC application, HikariCP is selected when HikariCP is available and no other pool is explicitly selected.
That makes HikariCP a natural fit for many Oracle-backed Spring Boot services. If your requirement is standard connection reuse, explicit pool limits, and clear timeout behavior, HikariCP keeps the application configuration small while still requiring real production sizing and validation.
In the sample application, the HikariCP profile uses a small pool on purpose so saturation is easy to observe:
Start with maximum-pool-size. In this profile, one application instance can hold up to five physical database connections from this pool. If all five are borrowed, the next request waits.
Next, look at connection-timeout. In HikariCP, this controls how long a request waits to borrow a connection before the pool gives up. HikariCP time values are expressed in milliseconds, so 2000 means two seconds. In the sample, the value is intentionally short so you can see timeout behavior without running a long test.
minimum-idle controls how many idle connections HikariCP tries to maintain. It is set here to keep two idle connections ready in the local lab. When minimum-idle is not set, HikariCP uses a fixed-size pool equal to maximum-pool-size; HikariCP’s documentation recommends that fixed-size approach for many production deployments. Your startup behavior, steady-state traffic, and database session budget should drive the final choice.
max-lifetime controls when physical connections are retired and replaced. Set HikariCP max-lifetime several seconds shorter than any database, network, or infrastructure-imposed connection lifetime that applies in your environment. Firewalls, load balancers, NAT gateways, database profiles, and managed service policies can all affect long-lived connections.
idle-timeout is also worth deciding explicitly when the pool is allowed to shrink. HikariCP’s default is 600000 milliseconds. It controls when idle connections above minimum-idle can be removed, and it should be reviewed with max-lifetime, Oracle profile settings, and any network idle limits.
validation-timeout controls how long connection validation can take. HikariCP’s default is 5000 milliseconds; the sample uses 1000 only to keep local failure behavior visible. The oracle.jdbc.defaultConnectionValidation data source property keeps the example aligned with lightweight Oracle JDBC validation. Avoid adding a custom connectionTestQuery just because an old example used one; HikariCP prefers JDBC4 Connection.isValid() when the driver supports it.
Oracle Maximum Availability Architecture guidance for HikariCP also calls out Oracle JDBC configuration details that are easy to miss. For production configuration, prefer the Oracle DataSource class approach when you need to carry Oracle JDBC properties deliberately, use JDBC4 validation rather than a hand-written validation query, and review Oracle JDBC connection properties such as oracle.net.CONNECT_TIMEOUT with the same care you give pool timeouts.
HikariCP is a strong choice when the pool’s job is to reuse connections, limit concurrent sessions, fail predictably when saturated, and expose behavior the application team can monitor through familiar Spring Boot patterns.
It is not a reason to skip production sizing. A simple pool can still be badly sized.
Oracle Universal Connection Pool is a JDBC connection pool for Oracle Database applications. It provides standard pooling behavior and adds Oracle Database-specific connection management features.
That combination is why UCP matters. It is the Oracle Database-focused pool for applications where the database topology and client pool are part of the same operational design.
If your Spring Boot application runs in an environment where the pool is expected to participate in Oracle Database operational behavior, put Oracle UCP on equal footing in the design discussion. That may include production designs involving Oracle Real Application Clusters (Oracle RAC), Fast Application Notification (FAN), Fast Connection Failover (FCF), Runtime Connection Load Balancing (RCLB), service-aware connection management, or related high availability patterns.
Those terms are easy to blur together, so keep the first definitions simple. Oracle RAC is an Oracle Database high availability architecture in which multiple database instances can provide access to a database through services. FAN propagates database service and instance events that UCP can consume for Fast Connection Failover when the required Oracle high availability and Oracle Notification Service configuration is in place. FCF uses those events so the client connection pool can react more quickly to certain failures by detecting and removing dead connections from the pool. Runtime Connection Load Balancing lets supported client configurations use database-provided advisory information when choosing where to create or borrow connections.
Enabling FCF is not just a naming choice in the application YAML. It requires fast-connection-failover-enabled: true, service-name based connections, and an Oracle Notification Service endpoint that is configured and reachable from the application host in the target topology.
These capabilities depend on the right database services, Oracle JDBC and UCP configuration, Oracle Notification Service and FAN setup where applicable, network configuration, and validation in the target topology. UCP can participate in Oracle-specific connection management; it does not remove the need for application-level exception handling, retry decisions, transaction design, or workload testing.
The local sample in this article uses UCP as a connection pool so you can compare basic pooling behavior under the same workload shape. It is not a replacement for high availability testing in a topology designed for that purpose.
The sample uses a ucp runtime profile. Use the Oracle Spring Boot Starter for UCP version selected for your Spring Boot line, and configure UCP through its own property model rather than translating HikariCP settings one for one.
A minimal UCP profile uses the same database connection information as the HikariCP profile, then sets UCP-specific pool controls. The important part looks like this:
In this lab, the ucp profile creates a UCP PoolDataSource explicitly and reads these spring.datasource.ucp.* values. The connection-pool-name gives DBAs and operators a useful name to find in monitoring and database session views.
The property names and units matter. In this sample, HikariCP uses a millisecond-valued connection-timeout, while the UCP profile maps connection-wait-timeout to seconds when configuring PoolDataSource#setConnectionWaitTimeout.
The sample deliberately sets initial-pool-size to 2 so local saturation is easy to see. If you omit initial-pool-size, verify the starter’s default behavior for the exact version you selected instead of assuming the pool starts at the size you expect.
When validate-connection-on-borrow is enabled, also decide the Oracle JDBC validation level deliberately. Validation behavior and cost depend on properties such as oracle.jdbc.defaultConnectionValidation, so carry a tested value such as LOCAL or another level chosen for the target environment.
Configure the profile around the behavior you need:
the maximum number of physical connections this application instance can open
the initial and minimum pool sizes
how long a request waits when the pool is exhausted
whether a connection is validated before it is borrowed
which inactive, abandoned, or lifetime settings fit the environment
whether your production topology needs fast-connection-failover-enabled, Oracle Notification Service configuration, service-name based URLs, abandoned connection timeout settings, or user-based borrowing with getConnection(user, password)
The ucp profile keeps the same workload shape as the HikariCP profile: the same database, endpoints, delayed request path, and load harness. That gives you an apples-to-apples way to observe local pool pressure without turning the article into a UCP high availability tutorial.
Oracle UCP becomes especially valuable when those basic settings are only part of the story. If the production environment expects the client pool to react to Oracle Database service events, planned maintenance, instance changes, or load-balancing advisories, choose and validate UCP with the DBA and platform teams.
The useful question is not “Which pool is always faster?” It is “Which pool matches the operational contract this application has to meet?”
Choose HikariCP when the application needs standard Spring Boot JDBC pooling and your team wants the behavior Spring Boot commonly provides out of the box. That is a common, solid choice. You want connection reuse, an explicit pool limit, predictable wait timeout behavior, and observability. Your platform may already have HikariCP standards, metrics, alerts, and incident playbooks. If those standards meet the application’s operational requirements, HikariCP is a good fit.
Choose Oracle UCP when Oracle-specific connection management is part of the requirement. That usually means the pool is not just an application-local optimization. It is part of the Oracle Database operational design. If production uses Oracle RAC or a service-based Oracle Database architecture, and the application is expected to participate in FAN, FCF, RCLB, or similar service-aware behavior, bring UCP into the design early with the DBA and platform teams.
HikariCP can still be configured with Oracle JDBC and Oracle Maximum Availability Architecture recommendations. The distinction is not that HikariCP is outside the Oracle story; it is that UCP is the Oracle Database-focused pool to evaluate when the pool itself needs UCP-specific capabilities such as FAN, FCF, or RCLB integration in a supported topology.
Follow the platform standard when your organization already has one that is tested and meets the requirement. A standard is more than a dependency choice. It should include timeout policy, connection string patterns, monitoring, session budgets, alerts, and an incident playbook. If the application needs something the standard does not provide, bring that requirement to the platform discussion.
A simple decision flow works well:
If your application needs standard Spring Boot JDBC pooling and your platform already uses HikariCP successfully, choose HikariCP.
If your application needs Oracle-specific connection management or high availability-related integration, choose Oracle UCP.
If your DBA or platform team has a standard for Oracle-backed services, follow that standard unless your application has a clear reason to differ.
In either case, test with the same workload shape your application expects in production.
Choose the pool that matches the application’s operational contract. HikariCP is a strong path for standard Spring Boot pooling; UCP is a strong path when Oracle-specific connection management or high availability-related behavior is required.
Treat performance as workload-specific. A pool that behaves well for short lookup queries may behave differently for longer transactions, bursty retrieval workloads, embedding metadata writes, or scheduled batch work. The local harness below helps you see pool pressure and timeout behavior, but it is not a universal benchmark.
Capability Comparison in Plain English
HikariCP and Oracle UCP overlap in the basics. Both can reuse JDBC connections, set maximum pool size, control how long a request waits for a connection, validate connections, expose operational signals, and make connection pressure visible when demand exceeds capacity.
The difference is what each pool is trying to be.
Use HikariCP when the application needs standard Spring Boot JDBC pooling, compact configuration, and the behavior your platform already expects from Spring Boot defaults. Its configuration vocabulary is familiar to many Spring teams: maximum-pool-size, connection-timeout, minimum-idle, max-lifetime, idle-timeout, and validation-timeout.
Use Oracle UCP when the pool is part of the Oracle Database operational design. UCP adds Oracle-specific connection management controls such as named pools, UCP-specific timeout and abandoned-connection settings, service-aware connection behavior, FCF and FAN integration in supported topologies, and RCLB-related behavior when the database, Oracle Notification Service, service names, driver, and pool settings are all configured for it.
The practical comparison is not “basic versus advanced” or “fast versus slow.” It is “standard Spring Boot pooling contract” versus “Oracle-specific database operations contract.” Both are strong choices when they match the contract. The lab design below focuses only on the shared pooling basics so the first run stays small and reproducible.
Try it Yourself: One Spring Boot App with Two Pool Profiles
Both profiles connect to the same Oracle Database Free container, expose the same endpoints, and use the same load harness. That lets you change the pool while keeping the workload shape the same.
The local lab design runs the same Spring Boot application with either the hikari or ucp profile, then sends the same delayed workload to observe pool pressure.
Keep the repository layout intentionally small:
oracle-spring-pool-lab/
src/main/java/com/oracle/demo/poollab/...
src/main/resources/
application.yml
application-hikari.yml
application-ucp.yml
compose.yaml
pom.xml
scripts/
start-db.sh
run-hikari.sh
run-ucp.sh
load.sh
restart-db.sh
setup/
01-create-app-user.sh
load/
pool-saturation.js
README.md
Pin the core runtime pieces rather than relying on transitive drift:
the Spring Boot patch version used by the sample
JDK 21 or newer
the Oracle Spring Boot Starter for UCP version that matches your Spring Boot line
the resolved Oracle JDBC, UCP, HikariCP, and Oracle Notification Service artifacts
the Oracle Database Free image tag used by the lab
k6 installed on the Docker host for the local load harness
For the HikariCP profile, the Maven dependency set can stay close to normal Spring Boot JDBC. The sample uses Spring Boot web and JDBC starters plus Oracle Spring Boot Starter for UCP; the Oracle JDBC and pool artifacts then come from the resolved dependency tree:
Keep the dependency set clear enough that one pool, not both, owns the active DataSource. In this lab, the hikari and ucp profiles create their DataSource beans explicitly from profile-specific configuration. Record the final dependency tree in the repository so future upgrades are deliberate.
The application exposes three simple endpoints:
GET /health
GET /query
GET /query-with-delay?ms=...
The most important endpoint is /query-with-delay.
There is a subtle trap here. If you run a JdbcTemplate query and then call Thread.sleep(), the connection may already be returned to the pool before the sleep happens. That would not create useful pool pressure.
For this demo, the endpoint borrows a connection explicitly and sleeps before the connection is returned:
thrownewIllegalStateException("Interrupted during demo delay",interrupted);
}
StringdatabaseTime=queryDatabaseTime(connection);
returnMap.of(
"status","ok",
"profile",activeProfile(),
"pool",properties.getPoolLabel(),
"databaseTime",databaseTime,
"requestedDelayMs",ms,
"effectiveDelayMs",delayMs,
"acquisitionMs",acquisitionMs
);
}
}
The delay is intentionally inside the try-with-resources block, so the connection remains borrowed until the block exits. The endpoint also caps the requested delay because this is a local saturation demo, not a general-purpose sleep endpoint.
This is a teaching pattern for the local lab, not a production recommendation. Production code should avoid holding database connections while doing unrelated work.
Prerequisites for the Local Connection Pool Lab
The companion lab uses these prerequisites:
Linux with Bash
Docker and Docker Compose
JDK 21 or newer
Maven, unless you use the repository wrapper script
enough local memory and disk space for the Oracle Database Free container
k6 installed on the Docker host and run from that host, not from a separate k6 container
The repository’s compose.yaml uses Oracle Database Free and exposes the FREEPDB1 service on local port 1521. The setup script creates the local pool_app user. Validate the service name, username, and password against the exact image and initialization path used by the lab if you change them.
Local Run Flow for HikariCP and Oracle UCP
Start by copying the local sample environment file:
cp .env.example .env
The .env file contains local demo placeholders such as ORACLE_DB_PASSWORD. Do not reuse them for shared development, staging, or production environments.
Start the database from the repository root:
./scripts/start-db.sh
The script starts the Oracle Database Free container and runs the repository’s initialization path for the demo user. If you change the image, service name, username, or password, update both the database initialization files and the Spring profile configuration.
Wait until the database container is healthy before starting the application. You can check the container state with:
The exact timestamp and acquisition timing will differ on your machine. What matters is that effectiveDelayMs reflects the requested delay cap and that acquisitionMs rises when the pool is under pressure.
Now run the load harness:
VUS=20DURATION=30s DELAY_MS=750 ./scripts/load.sh
Stop the app with Ctrl+C, then run the Oracle UCP profile:
./scripts/run-ucp.sh
Run the same load again:
VUS=20DURATION=30s DELAY_MS=750 ./scripts/load.sh
The sample includes a scripts/load.sh wrapper that runs the same k6 script against whichever pool profile is active. k6 is a load-testing tool from Grafana Labs; install it on the Docker host and run the wrapper from that host so the script can reach the Spring Boot application at http://localhost:8080. If you run k6 from somewhere else, override TARGET_URL explicitly.
With a pool size around 5, 20 virtual users, and a delay around 750 ms, the sample design is intended to create pool pressure. You should see latency rise and may see failed requests if borrow wait time exceeds the configured pool timeout.
When a borrow request cannot be satisfied within the configured wait timeout, the pool throws an exception and the request fails unless your application handles it differently. In the lab, look for failed HTTP responses in k6 and pool timeout exceptions in the application logs.
That is the point of the demo.
What the Local Demo Shows—and What It Does Not Prove
A local load run shows how a Spring Boot connection pool behaves when application concurrency exceeds the configured pool capacity. It can help you observe request latency, failed requests, borrow timeout behavior, and connection pressure under one controlled workload shape.
A load run gives you two useful local signals without adding pool-specific code:
the k6 summary, which shows request latency and failed requests
the application logs, which show borrow timeout or database connection errors
The k6 summary gives you a request-level view:
HikariCP:
http_req_duration avg=2.24s p(95)=2.67s
http_req_failed 21.56%
http_reqs 269
pool_lab_success_200 211
pool_lab_controlled_503 58
UCP:
http_req_duration avg=1.76s p(95)=2.54s
http_req_failed 36.63%
http_reqs 333
pool_lab_success_200 211
pool_lab_controlled_503 122
Use those numbers carefully. They show how this sample behaves on your machine under one controlled workload shape. They do not prove that HikariCP or Oracle UCP is universally faster.
The important saturation shape is the same even when pools expose metrics differently: the pool reaches its configured maximum, no idle connections are available, and later requests wait until a connection is returned or the borrow timeout expires.
Try changing one thing at a time.
Increase DELAY_MS, and the endpoint holds connections longer.
Increase VUS, and more requests compete for the same pool.
Increase the maximum pool size, and local waiting may drop, but database connection and session demand rises.
Shorten the borrow wait timeout, and saturation becomes visible faster.
This is the lesson you want before production: pool behavior is system behavior. The pool, application concurrency, request duration, database capacity, timeout policy, and number of app instances all interact.
For AI applications, this is especially worth testing before a feature launch. A retrieval endpoint that performs vector search plus metadata reads plus chat memory writes may have a different connection profile than a simple CRUD endpoint. Measure the path your users will actually hit.
This local demo design does not prove production high availability behavior. Oracle RAC, Oracle Data Guard, Application Continuity, Transparent Application Continuity, FAN, FCF, RCLB, and service draining require the right database topology, services, driver settings, network configuration, and workload validation.
Optional Local Recovery Exercise
An optional local recovery exercise restarts the database container while the application is running:
./scripts/restart-db.sh
After the database container is available again, try a normal query:
curl-s http://localhost:8080/query
During the restart, requests may fail. Logs may show database connection errors. Borrow attempts may time out. After the database accepts connections again and the pool has discarded or replaced broken connections, simple requests should succeed.
This is useful because it lets you see the application’s local failure symptoms. Keep the scope clear: a local Oracle Database Free container restart is not the same as validating Oracle RAC failover, Oracle Data Guard role transitions, FAN, FCF, RCLB, service draining, Application Continuity, or Transparent Application Continuity.
Use this exercise as a quick resilience observation. Use an environment designed for high availability testing when those features are part of the production requirement.
Practical Defaults and Production Conversations
The sample values are teaching values. They are not production recommendations.
Before production, treat pool configuration as an application-and-database design conversation. Developers, DBAs, and platform engineers should agree on what the service is allowed to do and how it should fail under pressure.
Start with the pool size. If one application instance has a maximum pool size of 20 and you run ten replicas, that service can open up to 200 connections from those pools before you count other services, jobs, or administrative sessions. That might be fine. It might also be the thing that pushes a shared database service into trouble.
Make the maximum pool size explicit. Align the total across replicas with the database session budget. Include background workers and scheduled jobs in the estimate. AI applications often have ingestion pipelines, embedding jobs, or agent workflows that run outside the main HTTP request path, and those also need connection budgets.
Use explicit wait timeouts. A request that waits forever for a connection is hard to diagnose and unpleasant for users. A request that fails quickly with a clear signal is easier to alert on and easier to handle with a retry policy when the operation is safe to retry.
Watch request latency and pool wait behavior together. If request latency rises while the pool is saturated, the application is probably waiting on database connections. If pool usage is low while latency rises, the bottleneck is somewhere else.
Review connection lifetime settings with the platform team. Firewalls, load balancers, NAT gateways, database profiles, and managed service policies can all affect long-lived connections. The pool’s lifetime and validation settings should fit that environment.
Be careful with retries. A retry can help when the failure is transient and the operation is idempotent. It can make saturation worse when many clients retry immediately against the same exhausted pool. Retry policy belongs with timeout policy, not as an afterthought.
Use leak detection as a diagnostic tool, not a design strategy. The real fix is to return connections quickly and reliably. In Java, that usually means try-with-resources or framework-managed transaction boundaries that you understand.
For Oracle UCP-specific production work, bring the database topology into the conversation early. If Oracle RAC, FAN, FCF, RCLB, Application Continuity, or Transparent Application Continuity are in scope, validate them with the database services, driver settings, network configuration, and workload patterns that production will actually use.
For HikariCP-specific production work, make sure the team has clear guidance for pool sizing, timeout behavior, validation, metrics, and incident response. HikariCP integrates cleanly with Spring Boot, but it still needs operational standards.
A good production conversation covers:
expected request concurrency and workload shape
number of application instances and background workers
maximum pool size per instance
total possible database sessions from the service
Oracle Database service name and connection string
timeout behavior at the pool, HTTP server, gateway, and client
retry policy and idempotency
required Oracle high availability features
pool metrics, alerts, and database session monitoring
what to do when the pool saturates or the database is unavailable
That last point matters. A setting without an operational response is only half a design.
Choose by Operational Fit, Then Test
HikariCP is a strong choice for many Spring Boot JDBC applications that connect to Oracle Database. It is directly supported by Spring Boot auto-configuration, has a compact configuration model, and fits applications that need standard pooling behavior.
Oracle UCP is a strong choice when Oracle-specific connection management or high availability-related integration is part of the application’s operational contract. If the production design expects the pool to participate in Oracle Database service behavior, choose and validate UCP with your DBA and platform teams.
The companion lab design gives you a practical way to see the basics. Run the same Spring Boot app with the hikari profile and the ucp profile. Send the same delayed workload. Watch latency, errors, application logs, and timeout behavior.
Then take those observations into the production conversation.
Keep the pool size explicit, validate the dependency tree and local scripts when versions change, and choose the pool that matches the system you are actually building.
]]>https://redstack.dev/2026/06/11/oracle-connection-pooling-in-spring-boot-when-to-use-hikaricp-and-when-to-use-ucp/feed/04655A Tale of Two Agents: Why we can’t go past CrewAI
https://redstack.dev/2026/06/10/a-tale-of-two-agents-why-we-cant-go-past-crewai/
https://redstack.dev/2026/06/10/a-tale-of-two-agents-why-we-cant-go-past-crewai/#respondWed, 10 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4644Continue reading →]]>
Key Takeaways
Codex was worth testing because it appeared to reduce the need for separate direct API-key access to model providers while still keeping agent work close to the repository.
The hard part was not getting another tool to create plausible files once. The hard part was preserving the behavior that made the workflow trustworthy across repeated runs.
For this repository workflow, CrewAI remained the better production runner because its task model fit our need for ordered stages, artifact contracts, guardrail hooks, review separation, and repository-level observability.
The broader lesson is not that one agent tool is universally better than another. When agent work becomes production work, evaluate the runner and the operational constraints around it, not only the model or the prompt.
It was the best of agents, it was the worst of agents… it is, after all, the age of agents…
I have been working with agentic AI in earnest over the last several weeks. I started with CrewAI for no special reason – I had learned about it in an agentic AI course, so it was a natural choice to start experimenting. But I can to realize that there are several things about it that I really like, and which don’t seem to hold true for other agentic platforms.
My favorite things about CrewAI:
All of the agent and task defitions, and the extra knowledge, can be stored in YAML file outside of the code proper, making both easier to maintain
It gives a lot of control over parallelization, fan-out, and so on
It lets you create deterministic guardrails easily
It’s python-based and easy to integrate with Oracle AI Memory Core, which I have written about recently, and which I firmly believe dramatically improves performance, acccuracy, etc., for agentic systems
You can easily use different models and effort/reasoning levels for different tasks – which let’s you optimize token use, and is great for LLM-as-a-judge tasks
It has excellent observability, explainability and evaulation options available, e.g., Arize Pheonix has great integration
And, perhaps most importantly, it faithfully respects the workflow and guardrail constraints, and it does so deterministically, not probabalistically
And one more thing – for bonus points – it seems to be much easier to run multiple parallel instances of the agents to work on different jobs at the same time – compared to the Codex alternative described in this article
There came a time when it appeared that I may need to find an alternate plaform, primarily driven by availability of API access to models, and this lead me to explore Codex native agents, to be clear – not OpenAI Agent SDK, but the .agents/skills/... setup in Codex itself.
To my great surprise, especially since I was using the exact same model in both cases, I found that Codex seemed to lack many of the things that I really liked about CrewAI, and it was very difficult to get it to perform tasks reliably. It felt to me like it lacked self-awareness – it constantly made what I would call silly mistakes, it constantly ignored instructions, and it constantly introduced regressions.
So, when the API access situation constraint ceased to be a real constraint, it was a very easy decision to abandon the ill-fated Codex agent experiment, and go right back to CrewAI.
Just to give some context, the agentic system we’re talking about in this article has about 28 agents, 70 tasks, 12 different workflows/pipelines, over 1000 lines of deterministic validation functions (guardrails), shared, persistent memory, and produces several kinds of artifacts, including documents and code. It has some very well defined phases, but within those phases significant opportunity for parallelization. It does use a number of tools, and it also uses the Oracle AI Database Skills that I have written about recently.
By the way, I did recently write about my experiences working with Codex to develop real-world software, which I suggest is an interesting companion read to this piece.
Here’s our story.
Once an agent workflow starts producing useful results, the next question is not “Can the model do the task?” It is “Can the system do the task again next week, with enough evidence that someone else can trust the result?”
That question pushed us to compare two different centers of gravity for repository-based agent work: a CrewAI-based runner and a Codex-based workflow that initially looked easier to operate without separate direct model-provider access.
Codex got much farther than a quick proof of concept. It helped improve the system. It exposed weak assumptions, suggested useful validation checks, and made several implicit contracts more visible. But once model access no longer looked like a hard constraint, the production tradeoff changed, and we kept CrewAI as the runner for this workflow.
By runner, I mean the part of the system that turns work definitions into executed behavior. It sequences tasks, enforces contracts, records what happened, and gives operators enough evidence to decide whether a run is ready to trust.
The lesson was not “Codex failed.” The more useful lesson was this: Codex helped us improve the system. CrewAI was still better at being the system.
Side note: In Embabel, a Java-based agentic AI platform, like CrewAI – the workflow definitions and guardrails are deterministic, i.e., they are code – they are not the LLM making a decision. I think this is an essential ingredient for a successful agent implementation. It’s a case of using the right tool for the job – LLMs are great at some jobs, but that doesn’t mean they are great at every job.
Why a Codex-Based Workflow Was Worth Trying
The attraction was practical before it was architectural.
The first attraction was model access. At the time, Codex looked like a way to run agent work without arranging separate direct API-key access to underlying model providers. For a repeatable workflow, that would have removed a practical adoption problem.
That now appears not to be a hard constraint. Once that changed, the case for replacing the production runner became much less about access and much more about operational fit.
Codex still had a second attraction: it is documented as a coding agent that can read, edit, and run code. That made it a reasonable tool to test around a repository-heavy workflow where fixes often happen in code, configuration, validation scripts, task definitions, or supporting artifacts.
Repository proximity matters. When an agent workflow breaks, the problem is not always the prompt. Sometimes the issue is a brittle validator, a missing artifact check, an unclear task contract, or a convention that exists only in someone’s head. A coding agent close to the repository can be very useful in that repair loop.
Codex was useful in that neighborhood. It helped make assumptions explicit. It pushed us to describe roles, task expectations, validation references, and collaboration contracts more clearly. The clearer those contracts became, the better the Codex workflow became.
But improving a system is not the same job as running it. And once model access stopped being the forcing function, running the system well became the deciding question.
For this workflow, the production runner had to do more than help with implementation changes. It had to preserve ordering, outputs, review boundaries, guardrail behavior, and enough observability for an operator to understand a run without replaying the whole conversation.
That is where the tradeoff changed.
What the Runner Had to Preserve
The workflow we started with was not a single prompt and a style guide. It was a staged production system.
Some stages can run with more independence. Others need a deliberate order. A review is not useful if the thing being reviewed has not settled. A release bundle is not useful if it cannot find the expected outputs. A status report is not useful if it says a stage ran but cannot tell you what it produced.
That is where artifact contracts become important.
An artifact contract is the expectation that a task writes specific files, metadata, or outputs in predictable places and formats, so downstream stages can rely on them.
Here is a simplified example. This is not a production path from any repository:
Expected by the workflow: reviews/final_review.md
Written by the runner: review/final_quality_report.md
The content might exist, but the contract is still broken. If a dashboard, metadata index, or downstream task expects one file path and the runner writes another, the workflow has created an operational problem.
That can sound fussy until you operate the same workflow more than once. Then it becomes essential infrastructure.
Stable file names are how dashboards render. Stable review paths are how people inspect a run. Stable metadata is how downstream tasks know what is ready. Stable validation reports are how we decide whether an output belongs in a release candidate.
So the replacement target was never “make another tool produce plausible output.”
The target was “make another runner execute the production workflow without losing the contracts that make the workflow operable.”
Everything else followed from that.
Structural Parity Was Easier Than Behavioral Parity
This became the central lesson of the evaluation: structural parity is not behavioral parity.
Structural parity means the workflow looks equivalent on paper. The right stages exist. The right task names appear. The right artifacts are requested. The final directory tree resembles the one you wanted.
Behavioral parity is harder. It means the workflow reliably behaves like the production system across runs. Tasks execute in a meaningful order. Review stages remain independent. Output contracts are followed consistently. Validation catches serious defects. Failure states are explicit. A weak stage does not quietly flow downstream as if everything succeeded.
For us, the hard part was not getting a Codex-based workflow to produce the right files once. The hard part was making the right behavior repeatable without live supervision constantly restating what counted as success.
That supervision is useful during design. You can inspect a weak output, tighten the instruction, add a validation step, and try again. Codex is productive in exactly that kind of loop.
Production workflows need more than attentive supervision. They need the runner to carry some of that burden.
A production runner needs to make distinctions visible. A review artifact should explain enough. Execution evidence should provide diagnostic value. Metadata should map the files downstream workflow expects. A stage name should correspond to distinct work, not only to a label in a directory tree.
A filename drifts, and suddenly an otherwise useful artifact becomes invisible to the part of the system that expected it.
Matching the nouns in a workflow is easier than matching the verbs. “Analyze,” “generate,” “review,” “validate,” and “package” are easy labels to reproduce. The behavior behind those labels is where the runner earns trust.
Observability Made the Difference Concrete
Observability was where the comparison stopped being philosophical.
For this repository workflow, observability does not mean “there is a log somewhere.” It means an operator can answer practical questions after the run:
Which tasks ran?
Which tasks produced which artifacts?
Which files were expected, and which were missing?
Which stages deserve closer inspection?
Which model or provider configuration handled a stage, where that metadata is available?
Did a review step do meaningful work?
Can this run be compared with a previous run?
Our CrewAI-based implementation had grown around those questions.
CrewAI’s task documentation describes tasks with fields for expected output, context, output files, callbacks, guardrails, and structured outputs. Our repository then layers run metadata and artifact checks around that execution model.
That distinction is important. CrewAI does not magically record every piece of evidence any team might want. We built a workflow around CrewAI that records the evidence we care about. CrewAI’s task model gave us building blocks that made repository-level observability practical: named tasks, declared output files, task context, guardrail hooks, and sequential or asynchronous execution where the design calls for it.
That is the standard the runner has to meet. Execution evidence that is structurally complete but operationally thin may be enough to make a dashboard row render, but it is not enough to build operator confidence.
A production runner should make the boring questions easy. What ran? What failed? What changed? What did it produce? What should I inspect next?
If the answer is “read the whole conversation and infer it,” the workflow is still too dependent on supervision.
Independent Checks Need Real Substance
Explainability in this kind of workflow is not model interpretability in the abstract. It is the ability to explain how the final output came to be.
What input shaped the plan? What did the technical review flag? What did validation check? What quality concerns were found? What changed before the final output? Why is the final output better than the first version?
A review file is not the same thing as a review.
For this workflow, we needed artifacts that explained what was checked, what changed, what remained uncertain, and which stage made that decision. Otherwise, the workflow could look complete while leaving us with very little evidence that independent review had happened.
Our CrewAI-based staged workflow gave us a cleaner path to that evidence. Technical review can be separate from general validation. Quality checks can be separate from improvement work. Validation can happen after the thing being validated is stable enough to check. Packaging can focus on whether the right public artifacts exist without pretending to be a technical review.
Separation alone does not guarantee quality. A weak review is still weak if it runs in its own task.
But independent stages create places where quality can be measured, compared, and improved. They also make failures more visible. If a review artifact is thin, we can see that the review stage underperformed. If an assessment misses a serious defect, we can tighten the rubric. If validation leaves uncertainty, we can decide whether to improve or hold the output.
For this workflow, the runner has to preserve that independence. If stages collapse into broad undifferentiated generation work, the output may contain files but still lack the evidence we need.
Better consistency checks help, and Codex helped us identify several of them. They did not replace the confidence we already had in the CrewAI evidence trail.
That mattered because the workflow was not only about generating text or code. It was about being able to explain why the result was ready.
Why CrewAI Still Fits This Production Workflow
For this repository, we chose CrewAI because it fit the production shape of the work.
The important pieces were tasks, context dependencies, output files, guardrails, guardrail retry behavior, and execution modes. Those map closely to what the workflow already needed.
CrewAI remained the better fit as the production runner, but not for free. It asks you to model the work as a workflow: agents, tasks, outputs, guardrails, and run artifacts. For a quick coding problem, that can feel like ceremony. For this production workflow, that ceremony was the point.
Here is a deliberately simplified YAML-like sketch, not exact CrewAI syntax and not copied from production. It shows the kind of contract shape we care about:
The value is not that YAML is magical. The value is that the workflow contract is reviewable.
A task can declare what it depends on, who should run it, what it is expected to produce, where the output should land, and what kind of guardrail should apply. The repository still has to validate that the expected files exist and contain useful evidence, but the contract has a visible place to live.
That matters when multiple people maintain a workflow. YAML-centered definitions can be reviewed in pull requests. They can be diffed. They can be discussed without reading the entire runtime implementation. They give reviewers and maintainers a shared object to inspect.
Execution order was another deciding factor.
Some stages must be sequential. Context should inform planning. Planning should guide production. Production should precede review. Improvements should respond to review. Packaging should happen after the required outputs and sidecars exist. CrewAI supports sequential execution, and our workflow uses that where dependencies matter.
At the same time, not everything needs to be serialized. Some supporting work can run asynchronously if the dependencies are clear. CrewAI gives us a mechanism for asynchronous tasks, while our workflow decides where parallel execution is safe.
That balance is exactly what a production runner should support: strong order where it matters, concurrency where it does not.
For this repository, CrewAI also gave us a clearer place to attach task-level guardrails. A guardrail is not a slogan. It is a workflow mechanism. In our implementation, guardrails are where we can encode checks for missing required sections, malformed outputs, broken artifact contracts, review stages with no findings and no explicit “no findings” statement, or validation reports that lack expected evidence.
CrewAI provides the hook; the workflow still has to supply the judgment.
Per-stage model configuration also mattered. We did not want one global “agent intelligence” setting for the whole workflow. Research synthesis, technical review, validation, quality checks, and packaging have different cost, risk, and reasoning profiles. In our CrewAI implementation, tasks are assigned to agents configured for those stages, so model and provider choices are part of the workflow design.
None of this means CrewAI is effortless. It is a framework, and frameworks create surface area. Bad task definitions still produce bad runs. Weak guardrails still miss defects. Observability only helps if we record the right evidence.
But for this repository, CrewAI let us encode more operational concerns in the workflow runner rather than relying on the surrounding conversation to restate them.
What Codex Still Does Very Well
We did not come away liking Codex less. We came away with a sharper sense of where it belongs in this workflow.
I want to be clear that we really, really tried to make Codex successful – we did a lot of reasearch, we learned about how other people have used it, we consulted best practices and reviewed other agentic implementations to work out where we were going wrong. This was not a casual test, we made real, concerted effort to get this to work satisfactorily before finally coming to the conclusion that it was not the right choice for this system
Codex remains useful close to the repository. In our workflow, it helped with code edits, repair loops, test ideas, validation checks, dependency updates, and implementation review. When a contract is vague, Codex can help make it concrete. When a validation artifact is missing, Codex can help design it. When the workflow has implementation bugs, Codex is useful in the repair loop.
The evaluation also improved our thinking.
The task-card style made us write down collaboration contracts more clearly. The comparison forced us to separate “file exists” from “stage did useful work.” The consistency checks that emerged from the exercise are worth carrying back into the CrewAI workflow.
That is a win.
There is also a broader lesson here for teams evaluating agent systems. For us, a coding agent was a strong place to evolve the workflow, while CrewAI remained the better place to run this repeatable system.
That is where we landed.
Codex helped us build and repair the system. CrewAI remained the better fit for running it.
The Decision, for Now
The decision is straightforward: CrewAI remains the production runner for this repository workflow. Codex remains part of how we improve the workflow.
We will keep using Codex where it shines: near code, near tests, near implementation repairs, near task-contract cleanup, and near validation design. We will keep carrying good ideas back from the comparison. We will keep tightening the CrewAI workflow with the consistency checks the work made obvious.
But the production run itself stays in CrewAI for now.
The reason is not that CrewAI is universally better than Codex. It is that this workflow is more than a conversation and more than a patch. It is a multi-stage production system with artifact contracts, review boundaries, execution dependencies, guardrails, observability, and assembly rules.
In that environment, the runner matters.
Other teams should make this decision based on their own workflow shape. If your workflow is mostly exploratory, coding-heavy, and interactive, Codex may be the right center of gravity. If your agent work is mostly pull-request repair, bug fixing, refactoring, or test generation, putting the agent close to the repository can be exactly right.
If your workflow is a repeatable production system, ask different questions.
What must run in order? Which artifacts are contractual? Which stages need independent review? How do you know a stage did meaningful work? What happens when a file is missing? Can you compare one run with the next? Can you recover from a partial failure? Can an operator trust the evidence without replaying the whole conversation?
Those questions pushed us back to CrewAI.
Conclusion: The Runner Has to Keep the Promises
Agent quality matters. Model quality matters. Prompt quality matters. But once agent work becomes production workflow, the runner matters too.
We learned that describing a workflow is easier than running one. Codex helped us describe, inspect, repair, and improve the system. It pushed us to make implicit contracts explicit. It generated useful ideas we will keep.
That is not a small contribution.
But the workflow also needed trustable operational properties: ordered execution, stable artifacts, useful diagnostics, review independence, guardrail hooks, repository-level evidence, retry hooks where appropriate, and per-stage control. For this repository, CrewAI gave us more of that in the runner structure we could build around.
That is the decision heuristic I would take from this evaluation: do not only ask whether an agent can name your process, draft your files, or produce the right shape once. Ask whether the runner can keep the promises your process depends on when nobody is watching every step.
]]>https://redstack.dev/2026/06/10/a-tale-of-two-agents-why-we-cant-go-past-crewai/feed/04644Helidon and Spring Boot, Working Together in One Microservices System
https://redstack.dev/2026/06/09/helidon-and-spring-boot-working-together-in-one-microservices-system/
https://redstack.dev/2026/06/09/helidon-and-spring-boot-working-together-in-one-microservices-system/#respondTue, 09 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4632Continue reading →]]>Key Takeaways
Helidon and Spring Boot services can work as peers when they share platform contracts instead of framework internals.
CloudBank V5 demonstrates those contracts through Eureka discovery, JWT/OIDC security, APISIX routing, and OpenTelemetry telemetry.
The Helidon customer service and Spring Boot account service each stay idiomatic while participating in the same operational system.
A live CloudBank V5 deployment shows the mixed services registered in Eureka and visible in SigNoz telemetry.
I have been working with a microservices application that includes both Helidon and Spring Boot services. That mix is not unusual. Real systems accumulate useful services over time. Different teams choose different frameworks for good reasons. Some services benefit from Spring Boot conventions, Spring Security, and the Spring ecosystem. Others are a good fit for Helidon, MicroProfile APIs, and a smaller service runtime.
The interesting question is not which framework should win. In an application that already has both, the practical question is how the services collaborate.
This article looks at that collaboration pattern through CloudBank V5, an example banking application that includes a Helidon customer service and Spring Boot services such as account. CloudBank and OBaaS give us a concrete deployment and operations environment, but they are not the point of the article. The point is interoperability: how Helidon and Spring Boot services can behave like one system when they agree on the right contracts.
In the CloudBank example, the shared contracts are:
service discovery through Eureka
authentication and authorization through Spring Authorization Server, OAuth2, OpenID Connect metadata, and JWTs
external API routing and route-level scope checks through APISIX
common telemetry through OpenTelemetry auto-instrumentation and SigNoz
Each service remains idiomatic inside its own framework. The integration happens at the system boundaries.
The Collaboration Model
Mixed-framework systems work best when the shared surface is small and explicit. The goal is not to make a Helidon service look like a Spring Boot service, or the other way around. The goal is to make both services understandable to the platform and to each other.
In CloudBank, that means a request can enter through APISIX, carry a JWT issued by the authorization server, resolve service targets through Eureka, reach either the Helidon customer service or the Spring Boot account service, and emit telemetry into the same observability pipeline.
That is the architecture in one picture. The gateway does not need to know the backend programming model. The registry does not need every service to use the same application framework. The authorization server publishes a token contract. The observability pipeline consumes telemetry in a common format.
The services collaborate because they share platform contracts, not because they share framework internals.
Discovery: One Registry for Different Runtimes
Service discovery is the first integration plane. A mixed-framework system needs a way to identify services without binding callers to pod addresses, Kubernetes internals, or framework-specific clients.
CloudBank uses Eureka as the service registry. The Spring Boot account service reaches Eureka through normal Spring configuration. Its application configuration gives the service a stable Spring application name and imports shared settings:
spring:
application:
name: account
config:
import: classpath:common.yaml
The shared Spring configuration supplies the Eureka client behavior:
eureka:
instance:
hostname: ${spring.application.name}
preferIpAddress: true
client:
service-url:
defaultZone: ${eureka.service-url}
fetch-registry: true
register-with-eureka: true
enabled: true
The Helidon customer service reaches the same registry through its deployment configuration. Its Helm values identify the service as a Helidon workload and enable Eureka registration:
fullnameOverride:"customer-helidon"
obaas:
releaseName:"obaas"
framework:"HELIDON"
eureka:
enabled: true
instance:
appname:"helidon-customer-service"
This is a good example of healthy interoperability. The two services do not need the same configuration syntax. They need the same operational outcome: each service has a stable identity and registers with the same discovery system.
That shared registry matters at the edge. CloudBank’s APISIX routes use Eureka discovery for upstreams. A route can target the ACCOUNT or CUSTOMER service identity without caring whether the implementation behind that identity is Spring Boot or Helidon.
The design rule is simple: let each framework configure discovery in its natural way, but make the service identity stable and visible outside the process.
In the live CloudBank deployment used for this article, Eureka shows Spring Boot ACCOUNT and Helidon CUSTOMER-HELIDON registered in the same service registry:
Security: Use the JWT as the Shared Trust Object
Security is the integration plane where framework differences can become painful if the architecture is not careful. Spring Security and MicroProfile JWT do not expose the same programming model. That is fine. They do not need to.
The shared object is the JWT.
CloudBank uses azn-server, a Spring Authorization Server service, to issue OAuth2 access tokens. APISIX exposes public authorization metadata and key endpoints:
/.well-known/* -> AZN-SERVER
/oauth2/* -> AZN-SERVER
Protected API routes require scopes. The route script creates read, write, admin, test, and transfer routes for the CloudBank services. For the customer and account thread, the relevant pattern is:
APISIX uses the OpenID Connect plugin in bearer-only mode. The route configuration points to authorization server discovery metadata and preserves the bearer token for the backend service:
The gateway check is important, but it is only the first layer. The backend service still validates the token and enforces resource-specific rules. That is what keeps authorization close to the data.
The Helidon customer service uses MicroProfile JWT. Its configuration points JWT verification at the same JWKS endpoint that the rest of the system uses:
Inside the service, the resource can work with the authenticated principal and token claims using Helidon and MicroProfile APIs. A compact version of the scope-checking pattern looks like this:
The Spring Boot account service validates the same kind of token through Spring Security. CloudBank’s shared Spring configuration points the resource server at the same JWKS location:
The frameworks are different, but the contract is the same:
the issuer is the authorization server
the verification keys are published through JWKS
the token carries the principal and scopes
APISIX checks broad route-level authorization
each service checks resource-specific authorization
That is a much cleaner integration point than trying to share framework-specific security code across runtimes.
Routing: A Consistent Edge Without Flattening the Services
APISIX gives the mixed system one external API edge. That edge can expose consistent routes and enforce coarse-grained route scopes while leaving each service free to use its own controller model.
The route script creates upstreams by service identity and discovery type:
{
"uri":"/api/v1/customer*",
"upstream":{
"service_name":"CUSTOMER",
"type":"roundrobin",
"discovery_type":"eureka"
}
}
That route is framework-neutral. APISIX needs a URI, an upstream service name, a discovery mechanism, and plugins. It does not need to know about JAX-RS annotations, Spring MVC annotations, CDI beans, or Spring components.
This gives the system a useful split of responsibility:
APISIX controls the public surface area.
Eureka resolves service identities.
Spring Authorization Server defines the token contract.
Helidon and Spring Boot services enforce the rules close to their resources.
CloudBank also shows why that split matters. The route script blocks external access to account journal endpoints by creating a deny-style route for /api/v1/account/journal*. The account service can still have internal endpoints for service-to-service work, but the gateway does not accidentally publish them as part of the public API.
This is the kind of boundary that lets teams mix frameworks without creating an accidental tangle. The outside API is deliberate. Internal implementation remains local.
APIs: Share Behavior, Not Annotations
The customer and account services do not need common controller annotations to interoperate. They need common API behavior.
The Helidon customer service exposes its API with JAX-RS style resources:
@Path("/api/v1/customer")
@Authenticated
publicclassCustomerResource{
@GET
@Produces(MediaType.APPLICATION_JSON)
publicResponsegetCustomers(){
...
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
publicResponsecreateCustomer(Customercustomer){
...
}
}
The Spring Boot account service exposes its API with Spring MVC:
Those programming models are different. The interoperability question lives one level up:
What does the authenticated principal represent?
Which scopes allow reads, writes, admin operations, tests, and transfers?
Which paths are public?
Which paths are internal?
Which service owns each business rule?
What JSON shapes and status codes do callers see?
Once those answers are stable, framework annotations become implementation details. A Helidon service can protect customer records using MicroProfile JWT and JAX-RS. A Spring Boot service can protect account records using Spring Security and Spring MVC. Clients and gateways interact with the API contract, not the controller framework.
This is also where integration tests should focus. A good mixed-framework test does not assert that both services are built the same way. It asserts that the same token identity produces consistent business behavior at both endpoints, that the same scope vocabulary is honored, and that callers see predictable HTTP results. That kind of test protects the contract without freezing either team inside the other team’s framework choices.
Observability: One Operational View
Interoperability is not complete if the services are only integrated at request time. They also need to be operable together.
CloudBank uses OBaaS OpenTelemetry support as the demonstration path. The Spring Boot account values enable telemetry:
otel:
enabled: true
The same values file identifies account as a Spring Boot workload:
obaas:
framework:"SPRING_BOOT"
The Helidon customer values identify the customer service as a Helidon workload:
obaas:
framework:"HELIDON"
The useful idea is platform-level instrumentation. Application teams should not have to invent a different tracing pipeline for each framework. With the OBaaS Java auto-instrumentation path, the platform can inject instrumentation and send traces, metrics, and logs toward the shared observability backend.
For day-two operations, this is a major part of the integration story. When a support engineer follows a request, the framework boundary should not become an observability boundary. A request to customer and a request to account should be visible in the same telemetry system, with service names, status codes, latency, and logs available from one operational view.
The SigNoz Services dashboard shows the same operational view from the telemetry side. In this run, the services list includes account, customer, and customer-helidon, with latency, error-rate, and operations-per-second columns coming from the shared OpenTelemetry pipeline:
SigNoz also receives trace data from the CloudBank request path. The deployment did not produce a single application trace containing both Spring Boot account and Helidon customer-helidon; the services are demonstrated here as separate participants in the same trace store. The first SigNoz capture shows a representative Helidon customer trace:
The second SigNoz capture shows a representative Spring Boot account trace from the same backend:
The same run validated the security path with live HTTP calls:
gateway_metadata=200
account_no_token=401
account_read_token=200
helidon_no_token=401
helidon_read_token=200
Those checks are intentionally contract-level checks. They do not prove that Helidon and Spring Boot use the same security implementation. They prove something more useful for interoperability: the same issuer and scope vocabulary can protect both service styles, and a scoped token can reach both the Spring Boot account API and the Helidon customer API.
Design Lessons Beyond CloudBank
CloudBank V5 is a convenient example, not a special rulebook. The same pattern applies to other systems that mix Helidon and Spring Boot.
First, give every service a stable identity. That identity should appear in discovery, route configuration, logs, traces, and dashboards. If the platform can identify the service consistently, the implementation framework can stay behind the boundary.
Second, standardize on a token contract. A shared issuer, JWKS endpoint, principal meaning, and scope vocabulary are more important than shared security code. Helidon can validate the token with MicroProfile JWT. Spring Boot can validate it with Spring Security. The architecture stays coherent because both services trust the same issuer and interpret the same claims.
Third, put public exposure at the gateway and data protection in the service. APISIX is a good place to define public routes and route-level scope requirements. It is not a substitute for service-side authorization. The backend still owns resource-level decisions.
Fourth, make telemetry a platform contract. Even when requests do not cross directly between Helidon and Spring Boot services, both frameworks should emit OpenTelemetry data into the same backend so operators can inspect each service from one place.
Finally, resist the urge to flatten the frameworks. Shared libraries can help inside a family of services, as CloudBank does with common Spring configuration for Spring Boot services. But Helidon and Spring Boot interoperability is stronger when the cross-framework contract is based on HTTP, JWTs, discovery, routing, and telemetry instead of a forced common programming model.
Closing
Helidon and Spring Boot can coexist cleanly when the architecture treats frameworks as local implementation choices and platform contracts as the shared language.
In CloudBank V5, the Helidon customer service and the Spring Boot account service collaborate through ordinary, durable boundaries: Eureka for discovery, Spring Authorization Server for JWTs and OpenID Connect metadata, APISIX for consistent routing and route scopes, and OpenTelemetry for a shared operational view.
That is the lesson I would carry into any mixed-framework system. Do not integrate frameworks by making them imitate each other. Integrate services by making the boundaries explicit.
]]>https://redstack.dev/2026/06/09/helidon-and-spring-boot-working-together-in-one-microservices-system/feed/04632Bringing OCI Generative AI into a Java Agent with Embabel
https://redstack.dev/2026/06/08/bringing-oci-generative-ai-into-a-java-agent-with-embabel/
https://redstack.dev/2026/06/08/bringing-oci-generative-ai-into-a-java-agent-with-embabel/#respondMon, 08 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4624Continue reading →]]>Key Takeaways
Embabel lets Java developers express agent behavior as typed actions and goals.
The GOAP-style planner uses available objects and action signatures to find a path to the goal.
OCI Generative AI can be introduced through a starter without rewriting the agent’s action code.
Deterministic Java code can prepare trusted context before the model writes the language-heavy part of the response.
Observability matters because agent behavior is a sequence of decisions and calls; Jaeger gives you a concrete way to inspect that sequence.
I was lucky enough to see a presentation from Rod Johnson at a meetup in New York recently. Rod is the creator of Spring, and his new project, Embabel, is fascinating. It’s a different kind of take on building agentic AI applications. I am particularly attracted to its use of method signatures as a way to deterministically create a goal, and the ease with which you can mix deterministic Java code with probabalistic LLM reasoning. It plays nice in existing Spring applications, uses the same conventions as Spring, so it’s already familiar to you if you come from that ecosystem.
Embabel is a very interesting project – because it does not ask Java developers to choose between “real code” and “AI code.” It treats the LLM as one participant in a typed application flow. Ordinary Java methods still do the parts that should be deterministic. The model does the parts where language, synthesis, and judgment are useful. Embabel sits between those pieces and works out how to get from the input you have to the goal you asked for.
That is a useful place to be if you already live on the JVM. A lot of enterprise software is not waiting to be rewritten into a new stack just because LLMs arrived. It already has Spring services, domain objects, tests, configuration, and deployment habits. Embabel plugs into that world and gives agentic code a shape Java developers can reason about: methods, parameters, return types, goals, and tests.
In this article we will use a new OCI Generative AI starter for Embabel. The starter lets an Embabel application use OCI Generative AI models through the same model abstraction the rest of the framework expects. The demo is a small travel briefing agent, but the interesting part is the architecture. It puts three kinds of work into one planned flow:
Parse a user request into a typed Java record.
Gather deterministic local facts with ordinary Java code.
Ask OCI Generative AI to turn those facts into a typed briefing.
The point is not the travel domain. The point is the shape of the application: deterministic code and probabilistic model calls in one planned flow, with Java types describing what each step consumes and produces.
What Embabel Is Doing
Embabel models an agent around a few core concepts: actions, goals, conditions, domain objects, and plans. The developer writes action methods. Each action method advertises what it needs through its parameters and what it produces through its return type. A goal describes a useful final state. At runtime, Embabel can infer a plan from the available objects, the actions it knows about, and the goal it needs to reach.
That makes the Java method signature more than a convenience. It is part of the agent contract. The method signature says, in a way the framework and the compiler can both see, “if you can give me a TravelRequest, I can give you LocalFacts.”
In an Embabel application, a method signature is not just implementation detail. It is part of the map the planner uses to decide what can happen next.
"The Chicago Riverwalk is a good base for architecture walks.",
"The lakefront trail gives an easy outdoor reset between indoor stops.",
"River North and Fulton Market have reliable coffee options near transit."
)
);
}
This action does not call an LLM. It does not need to. It accepts a TravelRequest and returns LocalFacts. When a later action needs LocalFacts, Embabel has a way to produce them.
Now compare that with the action that writes the final answer:
@AchievesGoal(description="A concise travel briefing has been prepared")
@Action
publicTravelBriefingwriteBriefing(
TravelRequestrequest,
LocalFactsfacts,
Aiai
){
varprompt="""
Write a concise two-day travel briefing in Markdown.
Use the supplied local facts. Keep the plan practical.
Mention why the deterministic facts and the LLM-written narrative both matter.
This method is still typed. It still takes explicit inputs. It still returns a Java record. Inside the method, the Ai helper calls the configured LLM and asks it to create a TravelBriefing. The model has room to write, but the application still decides where the model is allowed to act and what shape the result must have.
Why Goals Matter
Embabel’s default planning approach is based on Goal-Oriented Action Planning. In practical terms, GOAP lets the framework ask: given the objects currently available, which action can move the process closer to a desired goal?
For this demo, the starting object is a UserInput. The goal is a TravelBriefing. Embabel can see that:
parseRequest(UserInput) can produce TravelRequest.
gatherLocalFacts(TravelRequest) can produce LocalFacts.
writeBriefing(TravelRequest, LocalFacts, Ai) can produce TravelBriefing.
So the path is straightforward. In a larger application, this same mechanism becomes more valuable. You can add actions without rewriting a giant orchestration method. If a new action produces a type that another goal needs, it becomes part of the planning vocabulary.
That is the key difference between “call an LLM from Java” and “build an agentic Java application.” The former is a client call. The latter is a system of typed capabilities.
There is another practical benefit here: the plan is inspectable. If an agent run surprises you, you can look at the objects that were present, the actions that were eligible, and the goal Embabel was trying to satisfy. That fits the way many Java teams already debug applications. You do not have to treat the whole system as one giant prompt. You can ask smaller questions. Did the parser produce the right domain object? Did the deterministic action add the facts the model needed? Did the LLM action receive the right prompt? Did the final object satisfy the goal?
That debugging posture is one reason this style works well for enterprise Java demos. It keeps the model important, but it does not make the model responsible for everything. The more important the application is, the more you want boring pieces around the surprising piece: typed inputs, explicit outputs, repeatable tests, configuration that can be reviewed, and traces that show what happened.
Adding OCI Generative AI
The OCI starter is intentionally small from the application developer’s point of view. The demo depends on the starter and imports the Embabel dependency BOM:
The local OCI GenAI starter autoconfiguration registers OCI-backed chat and embedding model beans. The model definitions live in oci-genai-models.yml; the application can then select a default model through Embabel configuration:
For local development, the OCI starter can use the normal OCI config file authentication path. The important design detail is that the agent code does not change when the model connection is configured. The action asks for the default LLM; the platform supplies the OCI-backed model.
That separation keeps the demo from becoming a provider-specific tangle. The agent action is written in terms of Embabel’s Ai abstraction and the target Java type. OCI Generative AI appears in configuration and model loading. The Java method still says, “given this request and these facts, produce a TravelBriefing.” That is a good boundary. Application code owns the domain. Platform configuration owns the model connection.
The same boundary also helps with testing. The integration test does not need to contact OCI Generative AI to prove that Embabel can discover the actions, build the plan, and pass deterministic facts into the LLM step. It stubs the model response and verifies the application behavior around the call. Local deterministic tests catch ordinary mistakes quickly: missing beans, wrong action signatures, a prompt that forgot the facts, or a goal that cannot be reached.
The Demo Agent
Here are the domain records:
publicrecordTravelRequest(
Stringdestination,
intdays,
List<String> interests,
StringoriginalText
){
}
publicrecordLocalFacts(
Stringdestination,
List<String> facts
){
}
publicrecordTravelBriefing(
Stringdestination,
StringtripStyle,
Stringmarkdown
){
}
These records are not ceremony. They are the backbone of the agent. They tell Embabel what exists in the process at each step, and they tell the LLM exactly what object it must produce when the flow reaches the probabilistic part of the application.
The first action turns a free-form request into a simple typed object:
This is deliberately deterministic. A real application might use a database lookup, a rules engine, a customer profile, or a known catalog. Here, it is just enough code to show the boundary: not every step belongs in the model.
The final action uses the LLM, but it does so with a typed result:
Temperature is low because this is a practical briefing. We want enough language ability to make the result readable, not a wildly creative itinerary.
Notice what is not happening in this design. The prompt is not being asked to rediscover the whole workflow. It does not decide whether local facts should be gathered. It does not choose the action order. It receives a constrained job at the point where language generation is useful. The rest of the workflow remains normal Java. That is the difference between an agent that is merely “LLM-shaped” and an agent that can live inside an application architecture.
That split also gives reviewers a cleaner way to reason about risk. Deterministic code can be reviewed like deterministic code. The LLM prompt can be reviewed as a bounded language task. The trace can show whether the handoff between those two worlds happened where expected.
Running It
Start Jaeger first:
docker compose up -d
The example application assume you have install the OCI CLI and set up a profile so you can authenticate to OCI. Assuming you have done that, run the application with your OCI compartment and region:
mvn spring-boot:run
-Dspring-boot.run.arguments="Plan a two day visit to Chicago for a Java developer who likes architecture, coffee, and the lake."
The console output includes the question-driven answer produced by the agent:
=== Embabel OCI GenAI travel briefing ===
Destination: Chicago
Trip style: Java developer
# Chicago Briefing: A Developer's Two-Day Itinerary
This plan balances structured sightseeing with time for discovery, focusing on architecture, coffee, and the lakefront. It's built on deterministic facts (the reliable APIs of your trip) and a narrative layer (the application logic that creates a seamless user experience).
### Day 1: River, Loop & Classic Structures
* **Morning:** Start your day in River North. Grab a high-quality coffee at a local spot like Intelligentsia to fuel your exploration. The area is well-connected by transit.
* **Mid-day:** Head to the Chicago Riverwalk for the Chicago Architecture Foundation Center's River Cruise. It's the most efficient way to see dozens of iconic buildings and understand the city's history.
* **Afternoon:** After the cruise, walk along the Riverwalk for different ground-level perspectives of the canyon-like urban core.
* **Late Afternoon:** Walk south into the Loop to see foundational skyscrapers up close, including the Rookery Building and the Monadnock Building.
### Day 2: Lakefront, Modern Design & Fulton Market
* **Morning:** Explore Fulton Market, a former industrial district now known for tech offices and a vibrant food scene. Start with coffee at a neighborhood roaster.
* **Mid-day:** Head east to the Lakefront Trail for an outdoor reset. Rent a Divvy bike or walk a segment north of Millennium Park for skyline and water views.
* **Afternoon:** Make your way to Millennium Park. See Cloud Gate and Frank Gehry's Pritzker Pavilion.
* **Evening:** Return to Fulton Market for dinner.
The test suite also validates the same typed agent flow with mocked LLM output. That is useful because it proves the planner can get from UserInput to TravelBriefing and that the prompt receives the deterministic facts before you spend any cloud tokens.
mvn test
A successful run shows Embabel planning and executing the three typed actions, then Maven reports a clean test result:
Open Jaeger at http://localhost:16686 and search for embabel-oci-travel-agent. The useful trace is not only “there was a request.” It shows whether the agent run, action spans, and LLM call line up with the flow you intended to demonstrate. That makes tracing a sanity check for the agent design, not just an operations checkbox.
In the trace, the most useful thing to inspect is the shape of the run. You want to see the deterministic actions before the model-backed action, and you want the LLM call to appear under the action that writes the briefing. If the trace shows the model call happening before the facts are gathered, the problem is not the model. It is the application flow.
Here’s a different view of the trace, called a “flame graph”:
Enjoy!
]]>https://redstack.dev/2026/06/08/bringing-oci-generative-ai-into-a-java-agent-with-embabel/feed/04624Exploring Helidon AI: trace the recipe assistant with OpenTelemetry and Jaeger
https://redstack.dev/2026/06/05/exploring-helidon-ai-trace-the-recipe-assistant-with-opentelemetry-and-jaeger/
https://redstack.dev/2026/06/05/exploring-helidon-ai-trace-the-recipe-assistant-with-opentelemetry-and-jaeger/#respondFri, 05 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4615Continue reading →]]>Key Takeaways
OpenTelemetry tracing makes the Helidon AI request path inspectable without changing the assistant into a different application.
Jaeger gives us a local trace viewer for the demo; the instrumentation is application-created spans around the work we care about.
A stable recipe lookup is better than depending on a generated recipe id in a follow-on demo.
The trace proves the instrumented path ran in order. It does not prove that every model answer is correct.
In the first article in this follow-on series, the Helidon Eats app learned how to answer a recipe question with OpenAI, LangChain4j, Oracle AI Database vector search, and the same recipe data from the published Helidon Eats demo. In the second article, the assistant gained a memory model: working memory in JSON, semantic memory in vectors, episodic memory as events, procedural memory as rules, and a SQL property graph to connect the user, ingredients, and recipes.
That is enough behavior that a plain JSON response is no longer enough to explain what happened.
If the assistant says, “Try Tangy Rhubarb Salsa,” I want to know more than whether the final sentence sounds useful. Did the app embed the question? Did Oracle AI Database run the recipe vector search? Did the memory lookups run? Did the prompt get assembled after those lookups? Did LangChain4j call OpenAI chat? Which step took time?
That is what tracing is for.
Helidon SE can participate in OpenTelemetry, including configuration and APIs for tracing support, and the Helidon documentation describes its OpenTelemetry support as a preview feature in the Helidon 4.4.1 line Helidon OpenTelemetry docs. For this demo, I keep the instrumentation deliberately explicit. The application creates spans around the assistant path and exports them to Jaeger all-in-one over OTLP HTTP. Jaeger is the local viewer; the spans are created by our Helidon application.
Keep one repeatable request
Before adding tracing, I want a stable request path.
The request is the same one we have used throughout the demo:
GET /ask?q=what%20can%20I%20make%20with%20rhubarb
The answer should exercise the same pieces each time: question embedding, Oracle recipe vector search, working memory lookup, semantic memory vector search, procedural rule lookup, prompt build, and OpenAI chat.
There is a small but important database detail here. The recipe rows come from the already-published Helidon Eats article. The recipe ids are generated when the data is loaded. That means a hard-coded id is a poor anchor for a follow-on article. It may be correct in one validation database and wrong in another.
The demo now resolves the recipe from its stable content instead:
WITH target_recipe AS(
SELECT*
FROM recipe
WHERE recipe_title ='Tangy Rhubarb Salsa'
AND category ='Appetizers And Snacks'
AND subcategory ='Salsa'
FETCHFIRST1ROWONLY
)
SELECT recipe_id, recipe_title
FROM target_recipe;
That gives the rest of the demo a durable anchor. The generated id can vary, but the title/category/subcategory row is the one the published data set is meant to contain. The smoke test checks that the row exists exactly where the follow-on demo expects it.
This matters for observability because traces are easier to compare when the domain path is stable. OpenAI can still phrase an answer differently. That is fine. The application path should still be the same.
Add Jaeger to the local stack
The Docker Compose file keeps Oracle AI Database and adds Jaeger all-in-one:
services:
jaeger:
image: jaegertracing/all-in-one:1.76.0
environment:
COLLECTOR_OTLP_ENABLED:"true"
ports:
-"16686:16686"
-"4318:4318"
-"4317:4317"
oracle:
image: gvenzl/oracle-free:23.26.2-slim-faststart
ports:
-"15211:1521"
Jaeger documents the all-in-one image as a quick local way to run the collector and query UI together, with the UI on 16686 and OTLP ports on 4317 and 4318Jaeger getting started. That gives us a local trace viewer that is easy to start beside the database container. It keeps setup small while still giving every span a place to land.
The application points the OpenTelemetry exporter at the HTTP endpoint:
I am using OTLP HTTP here because it keeps the Java exporter configuration small. The Jaeger container also exposes the gRPC OTLP port if you prefer that path.
Create the tracer once
The app creates one small TracingSupport helper during startup. When OTEL_EXPORTER_OTLP_ENDPOINT is set, it builds an OpenTelemetry SDK tracer provider and an OTLP HTTP span exporter. When the variable is not set, it returns a no-op tracer.
For a tutorial app, SimpleSpanProcessor is easy to reason about. Each finished span is exported immediately. For a production service, I would usually use batching and a collector strategy, but that is not the point here.
The helper exposes two operations the rest of the app uses:
Spanspan(Stringname,SpanKindkind){
returntracer.spanBuilder(name)
.setSpanKind(kind)
.startSpan();
}
SpaninternalSpan(Stringname){
returnspan(name,SpanKind.INTERNAL);
}
That is intentionally simplistic. The useful part is not the helper. The useful part is deciding which work units deserve spans.
Then the interesting work gets its own child spans:
openai.embedding.question
oracle.recipe.vector_search
oracle.memory.working_lookup
oracle.memory.semantic_vector_search
oracle.memory.procedural_lookup
assistant.prompt.build
openai.chat.completion
This is the part that makes the trace readable. The spans are named for application work, not for implementation trivia. A reader can open the trace and follow the request path: embed the question, retrieve recipes, read memory, build the prompt, call OpenAI.
The Oracle vector search span records small, safe attributes:
That is enough to show that the vector search ran and returned Tangy Rhubarb Salsa as the first hit. It does not put the full recipe text in telemetry.
OpenTelemetry’s generative AI semantic conventions are useful, but they are marked as development, so I keep the mapping small and easy to change OpenTelemetry GenAI spans. I also avoid recording full prompts and full responses in spans. For this demo, counts, model names, selected recipe title, and memory hit counts are enough.
Bridge LangChain4j events into the trace
LangChain4j already gives us listener hooks for selected chat model implementations. The observability documentation describes ChatModelListener callbacks for request, response, and error events LangChain4j observability docs.
The demo keeps the existing listener, but now it also writes events onto the current OpenTelemetry span:
This does not mean LangChain4j magically traces the whole application. It means the model listener gives the application a clean place to attach chat model events to the openai.chat.completion span.
That distinction is worth keeping. Observability is better when it is honest about the boundary. Helidon serves the route. The app creates spans around the AI work. LangChain4j gives model hooks. Oracle AI Database performs SQL lookups and vector search. OpenAI handles embedding and chat calls.
Run the traced request
Start the containers:
docker compose up -d oracle jaeger
The Oracle container mounts startup/ as /container-entrypoint-startdb.d, so the database setup runs on each container start. The startup script loads the predecessor Helidon Eats recipe data when the food.recipe table does not already contain the Tangy Rhubarb Salsa anchor, applies the additive AI schema, and runs the smoke checks.
docker compose exec oracle
sqlplus -s food/Welcome12345##@FREEPDB1
@/work/sql/20-smoke-checks.sql
That smoke check should show one Tangy Rhubarb Salsa anchor, 500 recipe chunks, eight semantic memories, eight episodic events, four procedural rules, and the SQL property graph:
The answer can vary in wording, but the response should include the selected memory values and a recipe answer grounded in Tangy Rhubarb Salsa.
Then open Jaeger at:
http://localhost:16686
Search for the helidon-eats-ai service and open the GET /ask trace.
The trace summary above comes from the captured Jaeger trace. It shows the request-time path: the route span, the assistant span, the question embedding, Oracle vector search, three memory lookups, prompt build, and OpenAI chat call.
Read the trace as evidence
The trace answers a different question than the final JSON response.
The final response tells us what the assistant said. The trace tells us how the application got there.
In the captured request, the trace shows:
GET /ask
assistant.answer
openai.embedding.question
oracle.recipe.vector_search
oracle.memory.working_lookup
oracle.memory.semantic_vector_search
oracle.memory.procedural_lookup
assistant.prompt.build
openai.chat.completion
The Oracle vector span records two recipe hits and names Tangy Rhubarb Salsa as the first hit. The semantic memory span records one selected semantic memory. The working and procedural memory spans record that those values were present. The prompt-build span records the prompt length, not the prompt body. The OpenAI chat span records the model and response length, and it includes LangChain4j request and response events.
That is a useful level of evidence. It proves the instrumented path ran, in order, for that request. It proves the app did not skip memory retrieval before calling chat. It proves Oracle vector search ran before prompt assembly. It proves the model call happened after the grounded context was selected.
It does not prove the answer is always correct. It does not prove retrieval quality for every question. It does not prove anything about uninstrumented code. It does not give server-side timing inside OpenAI or Oracle. It gives application-side evidence for the spans we created.
That is still a big improvement over guessing.
Validate with the API too
The Jaeger UI is the nicest way to inspect the trace, but the API is useful for validation. A dashboard screenshot can show that a human saw the trace. A small API check can prove that the expected spans are present.
For the stable request, I like checking the service list first:
That returns the trace data as JSON. The fields are a little verbose, but they are deterministic enough for a smoke check. The request trace should contain these operation names:
GET /ask
assistant.answer
openai.embedding.question
oracle.recipe.vector_search
oracle.memory.working_lookup
oracle.memory.semantic_vector_search
oracle.memory.procedural_lookup
assistant.prompt.build
openai.chat.completion
That check is not glamorous, but it is a useful habit. It keeps the trace claim grounded. If the trace is missing oracle.memory.semantic_vector_search, then the request did not prove semantic-memory retrieval. If the trace is missing openai.chat.completion, then the app might have returned a setup response, failed before the model call, or hit a different path. The API check makes those cases visible.
It also separates two kinds of evidence.
The SQL smoke check proves the database state: 500 chunks, eight semantic memories, eight episodic events, four procedural rules, one working-memory row, and a graph edge from Tangy Rhubarb Salsa to rhubarb.
The /ask response proves the live route can call OpenAI and return an answer with selected memory.
The Jaeger trace proves the instrumented request path: embedding, vector search, memory lookup, prompt build, and chat completion.
Each one catches a different class of mistake.
Together, they make the demo much easier to trust.
Those are three different checks, and I want all three. When a demo combines AI, database retrieval, and memory, a single “it returned JSON” check is too thin.
Choose attributes carefully
Span attributes are where observability can become either very helpful or very messy.
The recipe vector search span records recipe.hit.count and recipe.first_hit.title. That is enough to confirm that the query returned two chunks and that the first one was Tangy Rhubarb Salsa. It does not record the entire chunk text. The semantic memory span records memory.semantic.hit.count, not the full memory document. The prompt-build span records prompt.length, not the prompt body.
Those choices are deliberate.
The most useful attributes are the ones that explain application decisions without turning telemetry into another data store. If the assistant starts returning odd answers, recipe.hit.count=0 is a strong clue. If memory.working.present=false, the request did not have the planning goal we expected. If prompt.length suddenly jumps from a couple thousand characters to tens of thousands, the prompt builder probably started including too much context.
Those are debugging signals. They are not secrets, and they are not the whole user conversation.
The same idea applies to the OpenAI spans. Recording gen_ai.system=openai, gen_ai.request.model=gpt-4o-mini, and embedding.vector.dimension=1536 is useful. Recording the API key would be a disaster. Recording the full prompt might be acceptable only in a local experiment with deliberate redaction. The default demo does not do that.
This is also why I prefer application-created spans for the teaching version. Automatic instrumentation is valuable, but explicit spans force us to name the application decisions we care about. For this assistant, those decisions are not hidden in the network stack. They are the recipe retrieval, memory selection, prompt construction, and model call.
Keep the trace useful
The most tempting mistake is to turn tracing into another place to dump everything. That usually makes traces noisier and less useful.
For this assistant, I would keep the default telemetry small:
model name
vector dimension
recipe hit count
first recipe title
semantic memory hit count
prompt length
response length
route name
tenant/session identifiers that are safe for the demo
I would not put API keys, full prompts, full recipe context, or complete model responses into spans. If a team needs prompt capture for a local experiment, make it explicit, temporary, and redacted.
The stable recipe lookup also remains useful as the assistant grows. If you change the retrieval limit, memory filter, prompt template, or model, run the same rhubarb request and compare the trace. The exact answer text may move around, but the application path should still be understandable.
That gives us a nice close to this part of the series.
Article 1 grounded the assistant in Oracle AI Database vector search. Article 2 gave it memory. Article 3 makes the request path visible. The assistant is still small, but it now has the pieces I want before adding more ambitious agent behavior: trusted data, useful memory, and a trace that shows how the answer was assembled.
]]>https://redstack.dev/2026/06/05/exploring-helidon-ai-trace-the-recipe-assistant-with-opentelemetry-and-jaeger/feed/04615Exploring Helidon AI: give the recipe assistant memory
https://redstack.dev/2026/06/04/exploring-helidon-ai-give-the-recipe-assistant-memory/
https://redstack.dev/2026/06/04/exploring-helidon-ai-give-the-recipe-assistant-memory/#respondThu, 04 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4608Continue reading →]]>Key Takeaways
Agent memory is easier to reason about when each memory type has a clear job and a separate storage shape.
Oracle JSON works well for working memory because session state changes shape as the user plans.
Oracle vector search works well for semantic memory, while SQL property graphs make relationship memory visible.
Keep retrieved memory selective so the prompt gets only the small working set needed for the current answer.
In the last article, the Helidon Eats application learned how to answer a recipe question. The route embedded the question with OpenAI, searched recipe chunks in Oracle AI Database, built a grounded prompt, and called OpenAI through LangChain4j.
That is a good first AI feature, but it is still a little forgetful. If I ask what to make with rhubarb, accept one of the suggestions, and then come back with a follow-up question, the assistant needs somewhere to keep the useful parts of that interaction.
Now we add that memory while keeping the same recipe domain and the same Helidon SE application. The goal is not to make a mysterious autonomous agent. The goal is to make the assistant remember the right things in the right place, and to keep those choices visible in the application response.
The demo stores four memory types and uses the current, semantic, and procedural pieces in the /ask path:
working memory for the current task state;
semantic memory for durable facts and preferences retrieved by meaning;
episodic memory for past events and outcomes;
procedural memory for task rules and routines.
It also adds relationship memory through a SQL property graph. The next article will take the same request path and instrument it with OpenTelemetry so we can inspect the whole run in a trace.
The useful constraint is that every memory path remains inspectable. We can see the schema, query it directly, call the Helidon routes, and decide whether the memory model is helping.
The separation is the main design choice. Working memory, semantic memory, episodic memory, procedural memory, and relationship memory should not collapse into one “memory” table just because the assistant eventually sees them in one prompt. They change for different reasons, they age differently, and they need different validation checks.
Helidon SE keeps the agent surface small: a few routes, a configuration object, and a service class. LangChain4j handles OpenAI chat and embeddings. Oracle AI Database keeps the state, vectors, JSON, and graph relationships in one database so the app can inspect what it is about to send to the model.
The seed data is intentionally big enough to test retrieval behavior. It uses one current working-memory document, eight semantic memories, eight episodic events, four procedural rules, and relationship edges over recipe and preference entities. That is still small enough to read, but it is no longer a one-row memory demo.
The request path then chooses a small working set from those stores. It reads the current JSON scratchpad, searches semantic memories by vector distance, selects the active rule for the task, and keeps the event and graph stores available for direct checks. That separation is useful because “memory” is not one operation. Some memory is state, some is retrieval, some is audit history, and some is relationship context. The assistant only needs a few of those values in the prompt, but the database keeps the fuller model available for validation and future routes.
That makes the demo easier to extend without making the prompt harder to understand.
Start with working memory
Working memory is the assistant’s current scratchpad. In the recipe app, that means the current planning goal, constraints, pantry items, and things to avoid.
That shape is one reason JSON belongs here. The working state may change as the conversation changes. Maybe we add budget, servings, leftovers, or equipment. I do not want to redesign a relational table every time the scratchpad gets one more field.
The app reads the current goal with a normal JSON query:
SELECT JSON_VALUE(state_doc,'$.goal')AS goal
FROM working_memory
WHERE tenant_id = ?
AND user_id = ?
AND session_id = ?
The assistant includes that goal in the prompt:
Working memory goal: find a use for extra rhubarb
That is enough for the first pass. The next refinement would be a route that updates the JSON document as the user accepts, rejects, or changes the plan.
Add semantic memory with vectors
Semantic memory is the durable “what we know” layer. In this recipe app, it can hold preferences such as:
The user is interested in tangy appetizer ideas and has extra rhubarb, red onion, and tomatoes.
The table mirrors the recipe chunk idea:
CREATETABLE semantic_memories (
memory_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
tenant_id VARCHAR2(80)NOTNULL,
user_id VARCHAR2(80)NOTNULL,
memory_text CLOBNOTNULL,
embedding VECTOR(1536, FLOAT32),
metadata JSON NOTNULL,
created_at TIMESTAMPDEFAULT SYSTIMESTAMP NOTNULL
);
The point is not that every preference must become a vector. The point is that some memories are useful by meaning rather than by exact key. “I need a quick dinner” might be close to stored preferences about weeknight meals even when the words are not identical.
In the first article, the app used OpenAI embeddings for recipe chunks. The same approach applies here. The app embeds a memory summary, stores it in Oracle, and later retrieves it with VECTOR_DISTANCE.
That gives the assistant two retrieval paths in the demo:
recipe context from recipe_chunks;
user or session context from semantic_memories.
On startup, the app embeds missing semantic memories with the same OpenAI embedding model it uses for recipe chunks. When a question arrives, it searches semantic_memories with VECTOR_DISTANCE, selects one relevant preference, and includes that text in the prompt alongside the recipe hits.
The app should still choose what to include. Memory retrieval is not a license to stuff every past fact into every prompt. For the recipe assistant, the demo retrieves one relevant preference and lets working memory decide the current task.
Record episodic memory
Episodic memory is event memory. It answers questions like:
What did the user accept last time?
Which recommendation failed?
Which substitution worked?
What did the tool call return?
The table is relational, with a JSON payload for the event details:
CREATETABLE episodic_events (
event_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
This is not chat history. It is a curated event stream. That distinction matters.
LangChain4j chat memory is useful for carrying recent messages through a conversation, but the LangChain4j documentation is careful to distinguish memory from full user-visible history. If the application needs an exact transcript, store that separately. Episodic memory is smaller and more purposeful. It keeps the events that should influence future behavior.
For the recipe assistant, episodic events are where I would store accepted recommendations, rejected recipes, allergy warnings, failed substitutions, and generated shopping lists.
Keep procedural memory as rules
Procedural memory is “how we do this task.” In a recipe assistant, that might be:
Prefer recipes from the Helidon Eats catalog. Never recommend ingredients listed in avoid.
The table is simple:
CREATETABLE procedural_rules (
rule_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
tenant_id VARCHAR2(80)NOTNULL,
task_key VARCHAR2(120)NOTNULL,
rule_text CLOBNOTNULL,
rule_version NUMBER DEFAULT1NOTNULL,
active CHAR(1)DEFAULT'Y'CHECK(active IN('Y','N'))NOTNULL
);
I like storing procedures separately from semantic memory because rules age differently from preferences. A preference might be updated when the user says “I like chickpeas.” A procedure should be versioned more deliberately because it changes the assistant’s behavior.
In the prompt, a procedural rule is not just another fact. The demo reads the active meal-plan rule and includes it as an instruction that constrains the answer:
Prefer recipes from the Helidon Eats catalog.
Never recommend ingredients listed in avoid.
For this demo, one active rule is enough; the useful part is that task rules stay separate from user preferences.
Add relationship memory with a SQL property graph
The four memory types are useful, but the recipe domain also has relationships:
a user likes an ingredient;
a recipe uses an ingredient;
a recipe matches a constraint;
an ingredient conflicts with an allergy;
a cuisine is related to a substitution pattern.
Those relationships fit naturally in graph form. The demo creates entity and edge tables:
The graph does not replace the tables. It gives the application a relationship-oriented query view over the same user, recipe, and memory data.
CREATETABLE memory_entities (
entity_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
entity_type VARCHAR2(40)NOTNULL,
display_name VARCHAR2(200)NOTNULL
);
CREATETABLE memory_edges (
edge_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
from_entity_id NUMBER NOTNULLREFERENCES memory_entities(entity_id),
to_entity_id NUMBER NOTNULLREFERENCES memory_entities(entity_id),
relation_type VARCHAR2(80)NOTNULL
);
It also links recipes to entities:
CREATETABLE recipe_entity_edges (
edge_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
recipe_id NUMBER NOTNULLREFERENCES recipe(recipe_id),
entity_id NUMBER NOTNULLREFERENCES memory_entities(entity_id),
The smoke script also runs a graph query over that property graph:
SELECT recipe_name, liked_ingredient
FROM GRAPH_TABLE (
eats_memory_graph
MATCH(u IS entity)
-[likes IS remembers]->(i IS entity)
<-[uses IS recipe_link]-(r IS recipe)
WHERE u.display_name ='mark'
AND likes.relation_type ='likes'
AND uses.relation_type ='uses'
COLUMNS (r.recipe_title AS recipe_name, i.display_name AS liked_ingredient)
)
ORDERBY recipe_name;
The result connects the user, liked ingredients, and recipes through the graph:
RECIPE_NAME LIKED_INGREDIENT
--------------------- ----------------
Tangy Rhubarb Salsa rhubarb
The graph is deliberately small. It proves the shape and gives the assistant a path for relationship memory that is separate from semantic similarity.
Try the memory checks
You need Java 21 or newer, Maven, Docker, Oracle AI Database Free running on FREEPDB1, and an OpenAI API key for the embedding and chat calls. The Helidon Eats food user owns the recipe tables, the duality view, and the additive AI objects.
After loading the schema, the smoke script checks each memory store:
The answer should recommend recipes from the stored recipe chunks, such as Tangy Rhubarb Salsa. The response also shows which memory values were selected for the prompt:
{
"workingMemoryGoal":"find a use for extra rhubarb",
"semanticMemory":"The user is interested in tangy appetizer ideas...",
"proceduralRule":"Prefer recipes from the Helidon Eats catalog..."
}
The output may vary in wording, but it should be grounded in the Oracle retrieval result and the selected memory. The useful checks are:
embeddedRecipeChunks reflects the selected recipe corpus;
the seed data has enough memory rows to exercise ranking and filtering;
embeddedSemanticMemories is 8;
the response shows the selected working, semantic, and procedural memory.
That gives us a compact test loop. We can validate memory rows with SQL and validate the model path with /ask.
Keep retrieval selective
The most tempting mistake with agent memory is retrieving too much. Once the app has four memory types, it is easy to say, “just load all of it.” That usually makes the assistant worse.
Working memory should be small and current. It answers, “what are we doing right now?”
Semantic memory should be retrieved by meaning and limited to a few relevant facts. It answers, “what does the assistant know that might help?”
Episodic memory should be curated by event type, recency, and outcome. It answers, “what happened before that matters now?”
Procedural memory should be selected by task. It answers, “which rules govern this job?”
Relationship memory should help connect entities. It answers, “how do these ingredients, recipes, constraints, and preferences relate?”
That is the pattern I would keep as the demo grows. The database can store more memory than the prompt should ever see. The application chooses the small working set for the current answer.
Where this leaves the series
The Helidon Eats application now has three useful layers.
The original recipe API gave us a clean application and database foundation. The first Helidon AI follow-up added OpenAI embeddings, Oracle vector search, and a grounded /ask route. Now the assistant has four memory types and a SQL property graph.
That is enough to make the assistant feel like part of the application rather than a model bolted onto the side. The recipe data stays in Oracle. The memory model stays inspectable. Helidon SE keeps the HTTP layer small. LangChain4j handles the model integration. OpenAI supplies the chat and embedding models.
There is plenty more you could add: memory update routes, graph queries in the prompt builder, richer metrics, or a UI. But the foundation is here, and it is a good one to build on. The assistant can answer from recipe data and remember what matters.
The next useful step is observability. Once a single answer can draw from vectors, JSON, rules, events, and a graph, we should be able to see that path as a trace instead of guessing which parts ran.
]]>https://redstack.dev/2026/06/04/exploring-helidon-ai-give-the-recipe-assistant-memory/feed/04608Exploring Helidon AI: add a recipe assistant to Helidon Eats
https://redstack.dev/2026/06/03/exploring-helidon-ai-add-a-recipe-assistant-to-helidon-eats/
https://redstack.dev/2026/06/03/exploring-helidon-ai-add-a-recipe-assistant-to-helidon-eats/#commentsWed, 03 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4603Continue reading →]]>Key Takeaways
Helidon SE can expose a small AI endpoint without turning the application into a framework exercise.
LangChain4j gives the app a clean Java path to OpenAI chat and embeddings.
Oracle AI Database can store the recipe text, JSON metadata, and vectors in the same place as the rest of the recipe data.
A useful first AI feature is not “chat with everything”; it is a grounded recipe question endpoint that retrieves a few trusted chunks and answers from those.
In the previous Helidon Eats article, the application was already in a good place for an AI feature. The recipe data was normalized, the API was small, and Oracle AI Database was already doing useful work with JSON Relational Duality Views. That is a nice starting point because an AI assistant needs more than a model call. It needs application data it can trust.
Let’s add a recipe assistant to the same style of application. The endpoint is deliberately modest:
GET /ask?q=what%20can%20I%20make%20with%20rhubarb
The route takes the question, embeds it with OpenAI through LangChain4j, searches recipe chunks in Oracle AI Database, builds a grounded prompt, and sends that prompt to OpenAI for the final answer.
I am using Helidon SE, LangChain4j, OpenAI, and Oracle AI Database Free. The demo keeps the dependency versions pinned in the build file so the commands are repeatable.
Helidon AI keeps this style of feature close to regular Helidon SE code. LangChain4j supplies Java abstractions for models, embeddings, listeners, and memory; Helidon keeps the HTTP and configuration layer small; the application decides which Oracle data is trusted enough to send to the model.
The important thing in this flow is where the grounding happens. The model does not get the whole database. It gets a small amount of context selected by the application. That keeps the endpoint understandable, and it makes the demo easy to inspect from both Java and SQL. It also gives us a narrow first feature that can be validated before we add richer agent behavior.
Start with the database shape
The recipe app already has structured recipe data from the previous article. The public domain LDJSON recipe data is loaded through recipe_dv into the normalized RECIPE, INGREDIENT, and DIRECTION tables. For the assistant, I add a second representation beside that existing data: short text chunks that are useful for semantic retrieval.
CREATETABLE recipe_chunks (
chunk_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
recipe_id NUMBER NOTNULLREFERENCES recipe(recipe_id),
chunk_text CLOBNOTNULL,
embedding VECTOR(1536, FLOAT32),
metadata JSON NOTNULL
);
The metadata column is JSON because the chunk carries small retrieval hints such as source table and category. The embedding column is a native Oracle VECTOR, sized for the OpenAI text-embedding-3-small model used by the demo.
I keep vectors in a separate chunk table instead of adding one vector column to RECIPE because the retrieval unit is not always the same as the source row. Today the demo creates one chunk per recipe. Tomorrow it could create separate chunks for ingredients, directions, notes, or nutrition text. The separate table also gives the embedding a small JSON metadata lifecycle without cluttering the source recipe table.
The chunk data comes from the same recipes that the first article exposed through the API. The seed keeps Tangy Rhubarb Salsa in the retrieval set by looking it up from the loaded recipe data using its title, category, and subcategory. That is more durable than depending on a generated numeric id. It also selects up to 499 more existing recipes from the loaded recipe table, so the assistant searches a bounded subset of the real demo data rather than a one-row toy corpus:
WHERE recipe_id NOTIN(SELECT recipe_id FROM target_recipe)
ORDERBY recipe_id
FETCHFIRST499ROWSONLY
)
)
SELECT recipe_id,
recipe_title ||': '|| description,
JSON_OBJECT('source'VALUE'recipe')
FROM selected_recipes;
I leave the vector empty in SQL and let the Java app populate it with OpenAI embeddings on startup. That keeps the stored vectors tied to the same embedding model the application will use at query time. It also shows the boundary I usually want in this kind of application: SQL creates the durable shape, and the application owns the model-specific embedding call.
The demo runs Oracle AI Database Free with the gvenzl/oracle-free:23.26.2-slim-faststart image:
services:
oracle:
image: gvenzl/oracle-free:23.26.2-slim-faststart
ports:
-"15211:1521"
environment:
ORACLE_PASSWORD:"Welcome_12345"
The Helidon app connects as the existing food user with password Welcome12345##. The AI objects are additive objects in the Helidon Eats schema, not a replacement schema with similar names. The setup separates the one-time admin step from runtime access: SYSTEM grants the setup privileges, and the Helidon app runs as food for the tutorial path. That keeps the example aligned with least privilege while preserving the application shape.
Add the Helidon route
The Helidon SE route is intentionally plain. The route does not need a lot of framework machinery to be useful.
WebServerserver=WebServer.builder()
.port(config.port())
.routing(routing -> routing
.get("/health",(req,res) ->
json(res,Json.object("status","UP")))
.get("/ask",(req,res) -> {
Stringquestion=req.query()
.first("q")
.orElse("What can I make with rhubarb?");
json(res,assistant.answer(question));
})
.get("/observe/ai",(req,res) ->
json(res,assistant.observe())))
.build()
.start();
The /observe/ai route comes back in the next article when we add the observability thread. For now it is enough to know that the AI path is not a black box. The app records request and response events from the LangChain4j chat model listener.
The configuration comes from environment variables:
The model names are not magic constants buried in Java code. They are normal deployment settings, which is enough for this demo.
Embed the recipe chunks
On startup, the assistant looks for recipe chunks that do not have embeddings yet. When OPENAI_API_KEY is present, it embeds each missing chunk and writes the vector back to Oracle.
The embedding model is a normal LangChain4j OpenAI model:
OpenAiEmbeddingModel.builder()
.apiKey(config.openAiApiKey())
.modelName(config.embeddingModel())
.build();
The repository writes the vector through SQL:
UPDATE recipe_chunks
SET embedding = TO_VECTOR(?)
WHERE chunk_id = ?
This is a useful place to pause. The application is not trying to hide Oracle behind an abstraction. LangChain4j handles the OpenAI embedding call. Oracle stores and searches the vector. The Java repository is the small bit of glue that makes the data flow obvious.
For this demo, startup ingestion keeps the example compact and repeatable.
Search Oracle with the question vector
When a user asks a question, the app embeds the question with the same OpenAI embedding model and passes that vector into Oracle.
First, the vector search is just SQL. We can join it to recipe rows, filter it later by category or subcategory, and inspect it with normal database tools.
Second, the application decides how many chunks to retrieve. The demo asks for two. That is enough to answer a small recipe question without dumping the entire corpus into the prompt.
After the app starts, a direct database check shows the chunks are embedded:
EMBEDDED_CHUNKS
---------------
500
And a simple vector-distance check returns the closest recipe chunk:
RECIPE_TITLE DISTANCE
-------------------- --------
Tangy Rhubarb Salsa 0
That output is just a sanity check: the vector column is populated, and Oracle can rank the recipe chunks.
Debug it in layers
One reason I like this demo shape is that every layer has a plain check.
Start with the database. Before the app calls OpenAI, the smoke script can prove that the recipe rows, chunk rows, working memory row, semantic memory row, episodic event, procedural rule, and property graph are present. At that point the vector columns are still empty, which is exactly what I expect before startup ingestion.
The graph check can go one step further and prove that the graph shape is useful, not just present:
SELECT recipe_name, liked_ingredient
FROM GRAPH_TABLE (
eats_memory_graph
MATCH(u IS entity)
-[likes IS remembers]->(i IS entity)
<-[uses IS recipe_link]-(r IS recipe)
WHERE u.display_name ='mark'
AND likes.relation_type ='likes'
AND uses.relation_type ='uses'
COLUMNS (
r.recipe_title AS recipe_name,
i.display_name AS liked_ingredient
)
)
ORDERBY recipe_name;
Then start the app with an OpenAI key. The first thing it does is embed the missing recipe chunks and semantic memory. That gives us a second database check: the counts for missing embeddings should drop to zero. If they do not, the failure is probably in configuration, outbound model access, or the vector update path.
Only after those checks does the /ask route matter. The route is useful because it exercises the whole loop: HTTP request, OpenAI embedding, Oracle vector search, memory lookup, prompt construction, OpenAI chat, and JSON response. If the answer looks strange, you can inspect the retrieved recipe names and selected memory before blaming the model.
That is also why I keep the endpoint small. A first AI feature should make it easy to answer simple debugging questions. Did we retrieve the right chunks? Did the prompt contain the selected memory? Did OpenAI return a response? Did the observability listener record the call? If those answers are visible, the application is much easier to improve.
Build the grounded prompt
Once the app has the recipe hits, it turns them into a small context block:
Stringcontext=hits.stream()
.map(hit -> "- "+hit.name()+": "+hit.text())
.collect(Collectors.joining("n"));
The prompt includes that retrieved context and a selected slice of memory:
Stringprompt="""
You are helping with the Helidon Eats recipe app.
Use only this recipe context and the selected memory.
The working memory line is a JSON document in Oracle that says what the user is trying to do:
{
"goal":"find a use for extra rhubarb",
"constraints":["appetizer or snack"],
"pantry":["rhubarb","red onion","tomatoes"],
"avoid":["peanuts"]
}
The semantic memory and procedural rule are the first hints of the fuller memory model in the next article. They are still selected by the application, not sprayed wholesale into the prompt.
I like this pattern because it keeps the prompt construction in application code. It is not scattered across the database, the model provider, and a hidden framework layer. You can debug it by logging the retrieved recipe names, checking the memory row, checking the selected preference, and reading the prompt template.
This is just enough instrumentation for the tutorial. The app knows when a chat request starts, when a response comes back, and which provider handled the call. In the next article, we will connect that to the memory path so the assistant is easier to reason about.
Try the endpoint
You need Java 21 or newer, Maven, Docker, an Oracle Free container, and an OpenAI API key for the mode=openai path.
Start Oracle. The Compose file mounts a startup directory into the database
container, so the same idempotent setup runs on every startup. It creates the
same food user when needed, loads the predecessor recipe data only when the
recipe table is empty, rebuilds the additive AI objects, and runs the smoke
checks from sql/20-smoke-checks.sql.
The response comes back as JSON. Here is the shape:
{
"mode":"openai",
"question":"what can I make with rhubarb",
"workingMemoryGoal":"find a use for extra rhubarb",
"semanticMemory":"The user likes tangy salsas...",
"proceduralRule":"Prefer recipes from the Helidon Eats catalog...",
"answer":"Tangy Rhubarb Salsa is a good fit..."
}
The exact wording can vary, but the important parts should be stable. Check whether the response stays within the retrieved recipe context; the demo prompt is designed to discourage answers outside those chunks.
The salsa preference is not coming from nowhere. The seed memory already says
the user likes tangy, salsa-style appetizers that can be served with chips, and
the working memory says the current goal is to use extra rhubarb for an
appetizer or snack. That is why the response and the AI observation path both
surface salsa-related context instead of making the recipe choice look like a
surprise.
You can also check the lightweight observability route:
curl"http://localhost:18080/observe/ai"
That returns database counts and the recorded AI events:
{
"database":{
"recipeChunks":500,
"embeddedRecipeChunks":500,
"semanticMemories":8,
"embeddedSemanticMemories":8,
"episodicEvents":8,
"workingMemoryRows":1,
"proceduralRules":4
},
"events":[
"chat.request provider=OPEN_AI",
"chat.response provider=OPEN_AI"
]
}
That is enough to prove the loop is alive: Helidon is serving the route, Oracle has the recipe vectors, LangChain4j is calling OpenAI, and the application can show a little bit of what happened.
Why this is a good first AI feature
The endpoint is intentionally small, but it has the pieces I want before adding more agent behavior.
The model call is grounded. The recipe context comes from Oracle vector search, not from a vague instruction to “answer about recipes.”
The data stays close together. Recipes, JSON metadata, vectors, and the first memory row all live in Oracle AI Database. That makes the example easier to validate than a demo spread across a database, a vector service, a cache, and a local file.
The application owns the policy. It decides how many chunks to retrieve, what memory to include, and when to call OpenAI. LangChain4j handles the provider mechanics, but the recipe app still reads like a recipe app.
The implementation stays close to the application concepts. There is a repository method for vector search, a prompt builder that shows the selected context, and a listener that records the AI call. Those are ordinary application seams, which makes the assistant easier to explain and easier to change.
That last point is the part I would protect as the application grows. It is tempting to turn every model-facing feature into a general chat endpoint. For Helidon Eats, a better path is to keep adding application-shaped capabilities: answer a recipe question, remember a planning goal, suggest two dinners, explain why a recipe matched the pantry, or show which memory influenced the answer. Each capability can still use OpenAI, LangChain4j, Oracle JSON, and vector search, but it stays tied to a user task the application understands.
The demo also gives us a clean next step. Right now the working memory row is only a hint. In the next article, we will turn that into a more complete memory model with working, semantic, episodic, and procedural memory. We will also add a relationship graph and make the observability endpoint more useful.
That is where the assistant starts to feel less like a search box and more like a small agent that can remember what it is helping with.
]]>https://redstack.dev/2026/06/03/exploring-helidon-ai-add-a-recipe-assistant-to-helidon-eats/feed/24603When Codex Comes to Town: A Software Story
https://redstack.dev/2026/06/02/when-codex-comes-around-a-software-story/
https://redstack.dev/2026/06/02/when-codex-comes-around-a-software-story/#commentsTue, 02 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4590Continue reading →]]>
I don’t believe that AI will take our software engineering jobs, I believe that those of use who embrace AI will see our jobs evolve and those who do not may end up in other jobs.
I want to share one of my experiences in this “brave new world” of writing software with AI. I am doing a lot of software engineering with AI these days, working together as peers. This is not “vibe coding” (I dislike that term) – this is real software engineering with an AI partner.
Most importantly, AI and I worked as a team. We wrote requirements first, we did several review cycles to make sure they were unambiguous and comprehensive. We spent at least two weeks writing tests before we wrote any code. We had over 400 tests covering almost all of the requirements before a line of code was written. We used modern Java features and capabilities, and best practices.
The application is not finished, but it is performing very well, and it is in production. It is not open source, so I cannot share the code with you. But my AI friend and I can share our story (which we wrote together too!).
YAAH (“Yet Another Attribution Helper”) is the fourth implementation of my US Patent 11,971,965 “System and method for determining attribution associated with licensed software code” (with co-inventor Dan Simone). The first implementation was written in Go by a person (me) and then got other contributors and grew in the usual way we are all familiar with until it became easier to write a new one than continue maintaining it.
The second implementation was an experiment in AI assisted coding, in Python, and it never got better than 80% accuracy no matter how hard we tried.
The third implementation was an attempt to create skills that an AI could use to do this work. It did not go well.
This implementation is written in Java, it uses modern Java features like virtual threads, records, pattern matching, and it follows the kinf of acrchitecture you’d more often find in a functional language like Haskell. Most of the work is in pure functions – they have no side effects, they produce the same output for the same input deterministically, no matter how many times you run them (and so can be memoized). And there’s a thin layer around the edge where all the side effects live – reading and writing files, cloning git repositories, and so on.
So it was written together, in partnership, really as equals, with AI assistants. I don’t think the specific choices are as important and the overall experience, but for those who want to know, I used GPT-5.5 with high reasoning as the “developer”, Claude Code (the latest available model at any given time, Sonnet 4.6 at the time of writing) as my “Architect” who performed most of the reviews, and Gemini 3.x (latest available) Pro and/or Flash as my “Product Manager” who performed a higher level review from time to time with a “Product” (with a captial “P”) hat on.
To give you an idea of the size of this application, it has about 15,000 words of requirements, around 36,000 lines of saved review comments and feedback; 28,000 lines of production Java code (in 224 files), 54,000 lines of test code (in 369 files), with a test-to-production ratio of almost 2:1.
A human (me) wrote 95% of the requirements (they were improved by AI over the course of the project as we discovered new edge cases) and AI wrote everything else.
The Problem Was Not Whether AI Could Write Code
I wanted to build something practical: a command-line tool that can generate a third-party attribution report for a source repository.
That sounds simple until you try to do it well. You need the application license, the copyright notices, and the full dependency graph. You need direct dependencies and transitive dependencies. You need to handle Maven, Gradle, Go, npm, Python, and LuaRocks without pretending they all behave the same way.
Then you need evidence for the exact dependency version.
That last word matters. If an application depends on version 1.2.3, the report needs evidence for version 1.2.3. Not the default branch. Not the nearest tag. Not whatever a repository shows today.
This is the kind of project where an AI-generated prototype can look impressive and still be wrong in ways that matter. A missing dependency, a license from the wrong branch, or a dropped copyright notice can make the output less useful.
So the real question became more interesting than “can AI write code?”
Could we use AI to build software with more discipline, not less?
YAAH became my answer to that question.
Start With the Contract
The first useful artifact was not code. It was our requirements document, which we lovingly called REQUIREMENTS.md. And we fully embraced RFC 2119 – if you have never read it, you really SHOULD.
The requirements were deliberately specific. YAAH had to support multiple ecosystems in one repository, collect recursive dependencies, keep uncertain dependencies unless a reliable test-only signal existed, cache source evidence, continue after ordinary dependency failures, and report those failures clearly.
It also had to preserve legal evidence.
That principle shaped the whole project. If a license or copyright notice might matter, prefer to keep it. Later rules can filter false positives, but the first version of the system should not casually throw evidence away.
This is where AI helped in a way that is easy to miss. Instead of jumping straight to implementation, I used AI to review the requirements.
It found contradictions and weak spots. The report format did not fully explain where non-canonical dependency license text belonged. Test-only dependency rules were too vague. Deduplication keys needed to be ecosystem-specific. Source repository lookup needed stronger rules. The architecture wanted pure functions, but the application also needed files, network calls, git operations, caches, and command execution.
That review was not glamorous, but it was one of the most important parts of the project.
Good AI coding starts before code. It starts by making the target hard to misunderstand.
Make the System Easy to Test
The architecture settled into three Maven modules.
yaah-core owns the domain model, workflow logic, evidence collection, report rendering, parsing, and semantic comparison. yaah-cli is the thin command-line entry point. test-util compares generated reports against reference reports.
That split paid for itself many times. The hard behavior lives in the core, while the CLI parses options and invokes the workflow. The comparison utility reuses the same parsing and semantic model instead of inventing its own understanding of the report.
The next design choice was even more important: separate pure logic from boundary work.
Pure logic can normalize dependency identities, compute dedupe keys, merge report blocks, sort output, classify test-only signals, and compare parsed reports. Boundary work reads files, calls package registries, runs Maven or git, fetches source archives, writes output, touches caches, and optionally calls an LLM.
Keeping that boundary explicit made the code easier to test and easier to change. It also made AI collaboration safer. When a bug showed up, we could ask for a fix in a specific component instead of handing the model a giant ball of side effects.
Build a Safety Net First
The first implementation pass was intentionally small.
The project started with the module skeleton, command-line smoke tests, basic domain records, dependency-list rendering, manual license override parsing, run options, and fixture catalog checks.
From there, the test suite grew quickly. There were tests for dependency identity, package URLs, source version selection, repository URL normalization, known license overrides, report parsing, semantic comparison, vulnerability warning ordering, copyright normalization, SPDX matching, and fixture behavior.
That test-first rhythm mattered because the project had too many edge cases for memory alone. The AI could move quickly, but the tests made it accountable.
Every time the implementation learned a new rule, the suite got another guardrail.
The repository eventually grew to hundreds of production and test files. That size is not automatically a virtue. The useful part was the shape of the growth: small services, typed records, focused tests, and visible review notes.
Let Real Fixtures Teach the Tool
The first fixture was toml-1.6.0, a small Go project with no third-party dependencies. It was perfect for proving top-level license and copyright output.
It was not enough.
A real attribution tool needs messy projects, so the fixture set grew. kingpin exercised Go dependency discovery and exact version checkout. httpx exercised Python metadata and multi-license behavior. Spring Boot Admin exercised Maven graphs, parent POMs, and monorepo subdirectories.
Larger fixtures pushed the tool harder. APISIX, external-secrets, SigNoz, LangChain Core, and LlamaIndex-related runs exposed source-resolution, caching, npm, Python archive, and performance behavior that smaller examples could not show.
That is where the project started to feel real.
Real packages do not politely follow your first design. They use vanity import paths. They publish source archives instead of clean git tags. They live inside monorepos. They use package names that do not match repository names. They put licenses in parent directories and code in subdirectories. They include generated files, examples, docs, vendored content, and old reports.
The fixtures forced YAAH to handle those patterns.
They also changed how we tested output. A byte-for-byte golden file would have been brittle, so test-util compares reports semantically. It can ask whether dependency membership changed, whether license sets changed, whether appendix entries changed, whether dependency errors changed, and whether the final error summary changed.
That made the tests much more useful. When a report changed, we did not just see “the file is different.” We saw what kind of meaning changed.
Prefer Evidence Over Silence
One of the best design decisions was to avoid fail-fast behavior for ordinary dependency problems.
If YAAH cannot resolve one dependency’s source repository, that should not destroy the whole report. The dependency should still appear, the error should be attached to that dependency, and the rest of the run should continue.
That design is practical because it gives the reader a useful report and a concrete list of what needs attention. It also makes the tool more honest. A dependency with a source-resolution error is different from a dependency that does not exist.
The same idea appears in the LLM integration.
YAAH can optionally use an LLM to review ambiguous copyright candidates, but only after deterministic filtering has done its work. The default is no LLM. When the LLM is used, the report includes audit lines in the relevant dependency block.
That is the right safety boundary: deterministic code for deterministic work, narrow LLM use where judgment helps, and auditable output when the LLM participates.
Keep the Ideas, Simplify the Mechanism
The original requirements mentioned an agent framework, and early planning used that vocabulary.
Later, we removed the framework mandate.
That was not a retreat. It was a good engineering decision.
The useful ideas stayed: small workflow stages, typed inputs and outputs, pure logic where possible, boundary adapters for side effects, and clear audit behavior. The framework dependency itself did not need to stay.
This is a useful AI-development lesson. The first plan is allowed to be wrong. The point is not to defend it. The point is to preserve the parts that proved useful and simplify the parts that did not.
After that cleanup, the project released its first snapshot and moved into the next phase: making the working system faster and more robust.
Make It Faster Without Losing Determinism
Once YAAH could produce useful reports, large repositories exposed the next problem: run time.
Processing dependencies one at a time is easy to reason about, but it does not feel good on a repository with hundreds or thousands of dependencies.
The performance work started with a plan, not a random thread pool. The rule was clear: parallelize independent dependency work, but keep the final output deterministic.
Report ordering, dependency-list ordering, final errors, license appendix ordering, and stdout behavior all had to stay stable. That led to virtual-thread dependency workers, bounded source scanning, cache cleanup, cache reuse, timing telemetry, and safer source materialization behavior.
The regression reports show why measurement mattered. Large fixtures exposed slow copyright and license evidence stages, and later runs showed much better throughput after scan controls and caching improvements.
The important point is not the exact timing number. The important point is the method: measure the run, make one class of improvement, run the fixtures again, record what changed, and keep the public output stable.
That loop is much better than asking an AI to “optimize this” and hoping for the best.
Use Regression Reports as Project Memory
The best artifact in the project might be the regression sweep process.
A full sweep builds the application, reads the fixture catalog, runs YAAH against the right fixture directories, saves the report and dependency-list outputs, scans for suspicious failures, runs semantic comparisons where reference reports exist, samples dependencies, and checks source evidence.
That is a serious workflow, and it gives AI a concrete job. Instead of “look for bugs,” the instruction becomes a repeatable runbook: run these fixtures, save these outputs, search for these failure patterns, compare these reports, sample dependencies, inspect evidence, and write down what changed.
That process caught real issues.
For example, one sweep found that a Python dependency had a correct MIT license, but the report also picked up generic prose about copyright law as if it were a copyright notice. That is exactly the kind of false positive you can get when the tool starts from a conservative inclusion rule.
The right response was not panic. It was a follow-up rule: tighten notice extraction for generic prose while preserving real legal notices.
That is how the project got better.
What AI Actually Did Well
The AI wrote code, of course, but that was not the most interesting part.
It helped review the spec. It wrote implementation plans. It identified missing tests. It wrote test scaffolding. It reviewed architecture. It made blunt lists of gaps. It ran fixture sweeps. It summarized regression results. It helped turn messy observations into reusable rules.
That is the pattern I would reuse.
Do not treat AI as a single coding step. Treat it as a collaborator that can play several roles if you give it enough context and enough checks.
The repository became that context.
The .ai directory held plans, reviews, and regression notes. Git held the sequence of decisions. Requirements held the contract. Tests held behavior. Fixtures held reality.
That combination made the collaboration durable. When the conversation changed, the project memory remained.
What I Would Recommend
If you want to use AI on a real software project, start with something more concrete than a prompt.
Write the requirements. Ask the AI to critique them. Fix the contradictions. Decide what must be deterministic. Decide where uncertainty is allowed. Write down how failures should appear to the user.
Then build the smallest testable slice.
Use real fixtures as soon as possible because they will teach you what the tidy examples hide. Keep the fixture catalog explicit, especially when a repository has a narrower run directory than its root.
Create a comparison tool if your output is structured. Text diffs are useful, but semantic diffs tell you what kind of behavior changed.
Keep regression instructions in the repo and make them boring enough to run again. A repeatable sweep is more valuable than a heroic one-time debugging session.
Most of all, use AI to make the engineering process more visible. Ask it to plan, but save the plan. Ask it to review, but commit the fixes. Ask it to run regressions, but keep the report. Ask it to generalize edge cases, then test the general rule.
That is where the leverage is.
Here’s a diagram that outlines the process that I am using more often than not with my AI team:
The Result
YAAH is now a real attribution helper, not just a demo.
It can detect several ecosystems, build dependency lists, resolve source repositories, select exact versions, collect license and copyright evidence, use caches, generate attribution reports, write dependency-list output, compare reports semantically, and run broad fixture regressions.
It still has work to do. Attribution tools always do. New package metadata shapes, source archive patterns, license oddities, and false-positive notices will keep showing up.
But the project has the right kind of foundation.
It has a contract. It has tests. It has fixtures. It has regression sweeps. It has review notes. It has a habit of turning surprises into rules.
That is the success story.
AI did not replace engineering discipline here. It helped us practice it more often.
There you go.
]]>https://redstack.dev/2026/06/02/when-codex-comes-around-a-software-story/feed/14590From GraphRAG Demo to AI System: Build a Minimum Viable Knowledge Graph with Oracle AI Database 26ai
https://redstack.dev/2026/06/01/from-graphrag-demo-to-ai-system-build-a-minimum-viable-knowledge-graph-with-oracle-ai-database-26ai/
https://redstack.dev/2026/06/01/from-graphrag-demo-to-ai-system-build-a-minimum-viable-knowledge-graph-with-oracle-ai-database-26ai/#respondMon, 01 Jun 2026 13:30:00 +0000https://redstack.dev/?p=4557Continue reading →]]>Key Takeaways
A useful GraphRAG project starts with one specific AI use case, not an enterprise-wide graph ambition.
The first production step after a demo is a minimum viable graph: the smallest useful set of entities, relationships, evidence, and service contracts.
Oracle AI Database 26ai is a good fit when you want relational data, vector search, SQL property graphs, and application metadata in one database workflow.
Treat the graph as a service layer for assistants, applications, analysts, and review workflows, not just as a retrieval trick.
In the first article, we built the mechanics of GraphRAG with Oracle AI Database 26ai. We parsed documents, created chunks, extracted entities and relationships, stored embeddings in VECTOR columns, defined a SQL property graph, and compared baseline vector search with graph-aware retrieval.
That is the right first milestone. You need to see the moving parts work.
The next question is different:
How do we turn this into an AI system that a team can actually use, evaluate, and grow?
That is where many graph projects get into trouble. It is tempting to say, “let’s build the enterprise knowledge graph”, then spend months arguing about the perfect ontology, the perfect taxonomy, and the perfect model of everything. That sounds serious, but it usually puts value too far away from the people who need it.
For AI systems, I prefer a smaller starting point: build a minimum viable graph for one useful capability.
Pick one bounded use case. Model only the entities and relationships needed for that use case. Store every relationship with evidence. Publish a few simple knowledge services over the graph. Then let the graph grow because people are using it, not because the diagram looked complete.
In this follow-up, we will take the GraphRAG schema from article 1 and reshape it into a practical Oracle pattern for AI systems:
a minimum viable ontology;
a minimum viable graph;
a few SQL views and queries that act like knowledge services;
a small context pack that an LLM or agent can use safely;
a review loop so extracted relationships improve over time.
This is less about a bigger demo and more about making the demo useful.
Start With The Question The System Should Answer
The graph should not start with “all customer data”, “all product data”, or “all documents”. That is too big to reason about and too easy to turn into a migration project.
Start with a question someone already cares about.
For example:
Which service reports explain why this asset failed, which parts were involved,
and which previous incidents look similar?
That one question gives us a useful first domain:
assets;
parts;
failure events;
service reports;
technicians or teams;
symptoms;
causes;
fixes;
supporting evidence.
Now the graph has a job. It is not just connecting data. It is helping an AI assistant retrieve the right evidence, explain why documents are related, and show the path from a user question to source material.
The important move is to choose one domain where relationship-aware retrieval matters. If plain vector search already answers the question well, keep it simple. GraphRAG is most useful when the answer depends on entities, relationships, paths, provenance, or several pieces of evidence that live in different places.
The Minimum Viable Graph Loop
Here is the loop I like for a first Oracle GraphRAG system.
The loop is deliberately small:
Pick one AI use case.
Define the minimum viable graph scope and the small ontology it needs.
Extract and load the minimum viable graph.
Publish knowledge services.
Evaluate answers and fix the graph.
The ontology is the vocabulary: entity types, relationship types, and rules. The graph is the instance data: this asset, this part, this service report, this failure event, this evidence.
Keep both small at first. A minimum viable ontology is not the final semantic model for the company. It is the smallest model that lets the use case work. A minimum viable graph is not every record in every system. It is the smallest connected set of evidence that lets a user get a useful answer.
That distinction matters because GraphRAG systems have two quality problems:
retrieval quality, which determines whether the assistant sees useful evidence;
graph quality, which determines whether the entity and relationship layer is trustworthy.
You can improve both only if the first graph is small enough to inspect.
Why Oracle Fits This Pattern
In article 1, Oracle AI Database 26ai was the database for chunks, embeddings, extracted entities, relationships, and the SQL property graph. That architecture is useful beyond the tutorial because it keeps several parts of the AI system close together:
source records and application data in relational tables;
document chunks and evidence text;
embeddings in VECTOR columns;
vector ranking with VECTOR_DISTANCE;
extracted entities and relationships;
SQL property graph metadata with CREATE PROPERTY GRAPH;
graph pattern queries with GRAPH_TABLE;
ordinary SQL views for application-facing services.
That last point is easy to underplay. A graph is valuable only when other parts of the system can use it. SQL views, stored procedures, REST endpoints, and application queries are the bridge between “we have a graph” and “the assistant can answer better questions.”
The key idea is not that every AI system needs every feature at once. It is that Oracle lets you keep the relational model, vector model, and graph model in one place while you decide which retrieval path the use case actually needs.
Add A Tiny Ontology Layer
The first article used these core tables:
documents
chunks
entities
entity_mentions
relationships
chunk_embeddings
For a more durable AI system, add a small ontology layer. This lets you control which entity and relationship types are allowed, which ones are active, and which ones need review.
('SERVICE_REPORT','A document or record that describes service activity');
INSERTINTO kg_relationship_types (
relationship_type,
description,
source_entity_type,
target_entity_type
)VALUES(
'INVOLVES',
'Links a failure event or service report to an asset, part, or symptom',
'FAILURE_EVENT',
'PART'
);
This is not a complete model. That is the point.
The first version should be small enough for a domain expert to say, “yes, those are the relationships we need”, or “no, this relationship should be split into CAUSES, REPLACED_BY, and OBSERVED_IN.”
That conversation is where the graph gets better.
Turn The Graph Into Knowledge Services
The SQL property graph is powerful, but most application code should not need to know the full graph query every time it needs context. Give the rest of the system a few simple services.
For a first GraphRAG-backed assistant, I would publish five services:
Entity lookup: find the canonical entity for a user term.
Entity context: return aliases, types, mentions, and nearby relationships.
Evidence pack: return source chunks that support a relationship or entity neighborhood.
Similarity search: return semantically similar chunks with Oracle vector search.
Answer context pack: combine graph facts and passages into one object for an LLM.
You can expose these as SQL views, PL/SQL functions, ORDS REST endpoints, or application service methods. The transport matters less than the contract.
The assistant should not be asking for “whatever is in the database”. It should be asking for a bounded context pack with evidence.
Demo: Entity Lookup
Start with a plain SQL view that gives applications a stable entity lookup surface.
CREATEOR REPLACE VIEW kg_entity_lookup_v AS
SELECT
e.entity_id,
e.canonical_name,
e.entity_type,
e.confidence,
COUNT(DISTINCT em.chunk_id)AS mention_count,
MAX(em.confidence)AS best_mention_confidence
FROM entities e
LEFTJOIN entity_mentions em
ON em.entity_id = e.entity_id
GROUPBY
e.entity_id,
e.canonical_name,
e.entity_type,
e.confidence;
Now an application can resolve a user phrase before it tries graph traversal.
SELECT
entity_id,
canonical_name,
entity_type,
mention_count
FROM kg_entity_lookup_v
WHERE LOWER(canonical_name)LIKE LOWER('%pump%')
ORDERBY mention_count DESC
FETCHFIRST10ROWSONLY;
This looks ordinary, and that is good. Not every part of a GraphRAG application needs to look exotic. A lot of the value comes from making the graph available through boring, dependable interfaces.
Demo: One-Hop Graph Context
Once the entity is resolved, use the SQL property graph to collect nearby facts.
This assumes the property graph from article 1, where entities are vertices and extracted relationships are edges. Adapt the property names to match your exact graph DDL.
SELECT
gt.source_entity_id,
gt.source_name,
gt.relationship_type,
gt.target_entity_id,
gt.target_name,
gt.evidence_chunk_id,
gt.confidence
FROM GRAPH_TABLE (
graphrag_entity_graph
MATCH(src)-[rel]->(dst)
WHERE src.entity_id =:entity_id
COLUMNS (
src.entity_id AS source_entity_id,
src.canonical_name AS source_name,
rel.relationship_type AS relationship_type,
dst.entity_id AS target_entity_id,
dst.canonical_name AS target_name,
rel.evidence_chunk_id AS evidence_chunk_id,
rel.confidence AS confidence
)
) gt
ORDERBY
gt.confidence DESC NULLS LAST
FETCHFIRST20ROWSONLY;
For relationship-heavy questions, this is the part plain vector search does not give you directly. The result is not just a passage that sounds related. It is a set of explicit facts with source evidence IDs.
Do not treat those facts as perfect. Treat them as extracted candidates with provenance. The assistant can use them, but the system should still keep evidence chunks close by.
Demo: Evidence Pack
The evidence pack joins graph facts back to chunks. This gives the LLM the two things it needs:
That is the first service I would put behind an assistant.
Given an entity, return the relationships the system knows about and the evidence that supports them. If this service is weak, the rest of the assistant will be weak too.
Demo: Add Vector Search Back In
Graph retrieval and vector retrieval solve different parts of the problem.
The graph is good at “what is connected to this?” Vector search is good at “what text is semantically close to this question?” For most useful assistants, you want both.
Now you can build a context pack from two sources:
graph facts and evidence chunks around matched entities;
semantically similar chunks from vector search.
Keep the scores visible. If the answer is based mostly on weak graph extraction, the UI or review log should show that. If the answer is based mostly on vector search with no graph support, show that too.
Demo: Build A Context Pack For An LLM
The context pack is the handoff between retrieval and generation.
I like to keep it boring and explicit. Here is a small Python shape:
fromdataclassesimportdataclass
@dataclass
classGraphFact:
relationship_type: str
target_name: str
confidence: float|None
evidence_chunk_id: int
evidence_excerpt: str
@dataclass
classRetrievedPassage:
chunk_id: int
title: str
distance: float
chunk_excerpt: str
@dataclass
classAnswerContextPack:
question: str
matched_entity: str
graph_facts: list[GraphFact]
vector_passages: list[RetrievedPassage]
Then make the prompt rules just as explicit:
Answer the user's question using only the graph facts and passages provided.
If the graph facts and passages disagree, explain the disagreement.
If the evidence is not enough, say what is missing.
For each important claim, include the source chunk ID.
Do not invent relationships that are not present in the context pack.
This is the part where GraphRAG becomes more than retrieval. You are giving the model a small evidence workspace with relationship facts, source passages, and instructions about uncertainty.
The LLM still matters. But the database is doing real work before the LLM ever sees the prompt.
What To Evaluate
Do not start by asking whether the graph is “good”. That is too vague.
Evaluate the services.
For a first pass, make a small spreadsheet or table with 20 to 40 questions. Include direct questions, relationship questions, and failure cases.
Useful columns:
user question;
expected entity;
expected relationship type;
expected source document or chunk;
baseline vector chunks;
graph facts returned;
final context pack;
answer result;
reviewer notes.
For each question, ask:
Did entity lookup resolve the right thing?
Did graph traversal return useful relationships?
Did the evidence pack include the source chunk?
Did vector search add useful passages?
Did the assistant cite evidence rather than make a leap?
Was the answer better than baseline vector retrieval alone?
That last question matters. GraphRAG adds moving parts. It should earn its place.
Some questions will not need graph context. Some will expose bad extraction. Some will show that your relationship labels are too broad. That is not a failure. That is the loop working.
A Practical Adoption Pattern
Once the first use case works, do not jump straight to “enterprise-wide”.
Add one adjacent use case.
If you started with service reports and asset failures, the next use case might be parts recommendations or known-issue discovery. That lets you reuse several entity types while adding only a few new relationships.
A practical adoption path looks like this:
One use case, one domain, one minimum viable graph.
Two or three knowledge services used by one assistant or application.
A review queue for low-confidence entities and relationships.
A small evaluation set owned by the team that cares about the answers.
A second use case that reuses part of the graph.
Shared entity resolution and relationship governance as the graph grows.
This is how the graph becomes an asset instead of a side project.
It also creates better conversations with business users. You are not asking them to approve a universal semantic model. You are showing them an assistant that can answer a hard question, then asking which terms and relationships need to be corrected.
That is a much easier conversation to have.
Keep The Human Review Loop Close
Automated extraction is useful, but it is not authority by itself.
In article 1, every relationship carried evidence text, an evidence chunk ID, a confidence score, and an extraction method. Keep that pattern. Then add review status.
WHERE r.review_status IN('PENDING','NEEDS_REVIEW')
ORDERBY
r.confidence ASC NULLS FIRST
FETCHFIRST25ROWSONLY;
This is one of the most important differences between a demo and a system. In a demo, extraction errors are annoying. In a system, extraction errors need a place to go.
Security And Governance Are Part Of Retrieval
If your GraphRAG system retrieves sensitive data, security cannot be bolted on after answer generation.
The retrieval layer should respect the same access rules as the application data. If a user cannot see a source document, the assistant should not see chunks from that document either. If a relationship was extracted from restricted evidence, the relationship should not leak that evidence through a graph answer.
At minimum, design for:
document-level access checks before chunks are retrieved;
entity and relationship filters for tenant, domain, or sensitivity;
audit logs for context packs sent to an LLM;
masking or redaction for sensitive fields;
separate review flows for high-impact relationships.
The nice thing about keeping this in Oracle is that you can use database-side controls and ordinary application authorization patterns close to the data. The hard part is discipline: apply access rules before building the prompt, not after the model has already seen the evidence.
Where This Leaves Us
Article 1 built the GraphRAG machinery. This article turns that machinery into a pattern a team can operate:
start with one relationship-heavy AI use case;
define the smallest useful ontology;
load the smallest useful graph;
expose the graph through knowledge services;
combine graph facts and vector passages into context packs;
evaluate the services;
review and improve the extracted relationships.
That is a more modest goal than building the grand graph of everything. It is also much more likely to survive contact with real users.
Once the first graph-backed assistant is useful, the next graph gets easier. You reuse entity resolution, evidence handling, service contracts, review queues, and evaluation habits. The graph grows because the applications are pulling it forward.
That is the path I would take: build the smallest graph that makes one AI system meaningfully better, prove it with evidence, and then let the next use case earn the next expansion.
]]>https://redstack.dev/2026/06/01/from-graphrag-demo-to-ai-system-build-a-minimum-viable-knowledge-graph-with-oracle-ai-database-26ai/feed/04557Four kinds of agent memory in Java with LangChain4j and Oracle AI Database
https://redstack.dev/2026/05/29/four-kinds-of-agent-memory-in-java-with-langchain4j-and-oracle-ai-database/
https://redstack.dev/2026/05/29/four-kinds-of-agent-memory-in-java-with-langchain4j-and-oracle-ai-database/#respondFri, 29 May 2026 13:30:00 +0000https://redstack.dev/?p=4552Continue reading →]]>Key Takeaways
For a Java agent, working, semantic, episodic, and procedural memory are best treated as access patterns over one governed Oracle AI Database-backed memory core, not as four separate stores.
The first article gave the agent durable semantic memory through LangChain4j’s OracleEmbeddingStore. This follow-up keeps that path and adds JSON working state, relational episodes, versioned procedures, memory edges, and an entity graph.
Oracle AI Database is a good fit for this shape because one database can support JSON state, vector-searchable facts, relational event history, CLOB procedures, and SQL Property Graph relationships. In this demo, those objects live in one application schema.
The app should not include every memory in every prompt. It should plan which memory types are useful, retrieve only those blocks, and make the selection visible.
Retrieved memory should be handled as context, not authority. In this demo, memory is placed below the system message; in production, keep it below system and developer instructions, scope it by tenant and user, and validate it before you let it influence important actions.
In the first article, we gave a Java agent durable semantic memory: selected facts stored in Oracle AI Database and retrieved by meaning through LangChain4j.
That is a useful starting point, but most agents need more than remembered facts. They need active state for the current task. They need a record of what happened last time. They need durable knowledge. They also need procedures that tell them how a task should be done.
Oracle’s AI Agent Memory provides a unified memory core with several kinds of memory. Oracle’s current Oracle AI Agent Memory library and the notebooks in the AI Developer Hub are Python-based, so this Java article borrows the architecture and implements the access patterns directly with LangChain4j and JDBC rather than using the Python package. We will extend the same Java 25 and LangChain4j demo from the first article.
The useful distinction is not “which product stores which memory.” The useful distinction is “how will the agent read this later?”
In this demo we use four memory types:
Working memory is the current state of the task: active goal, scratchpad, current plan, and short-lived context. We store it as a JSON row keyed by tenant, user, and session.
Semantic memory is durable knowledge: facts, preferences, summaries, and domain statements that should be retrieved by meaning. We keep using LangChain4j’s OracleEmbeddingStore.
Episodic memory is what happened: prior sessions, tool results, task outcomes, and troubleshooting events. We store it as relational event rows with timestamps and JSON payloads.
Procedural memory is how to do something: task rules, playbooks, preferences, and learned routines. We store it as versioned procedure text keyed by task.
There is one more piece that becomes important quickly: relationships. An episode may have used a procedure. A semantic memory may have been extracted from a particular session. A user preference may belong to a tenant, project, or customer. A place such as Paris may connect to sights, neighborhoods, constraints, and traveler preferences.
For the runnable demo we use both forms. A normal relational edge table explains links between memory records. A small SQL Property Graph explains links between entities such as the traveler, Paris, the Eiffel Tower, the Louvre, Montmartre, and Le Marais.
Map the memory types to Oracle AI Database
Here is the design we will implement:
The first article already created the semantic path with AGENT_MEMORY_STORE. This article adds the structured side around it.
The important thing is that each table matches a retrieval pattern:
Working memory is fetched by exact key: tenant_id, user_id, and session_id.
Semantic memory is requested through vector similarity with explicit metadata filters for tenant, user, session, and memory kind.
Episodic memory is fetched by tenant and user, ordered by recency. You can add event type, time window, or outcome filters as the application grows.
Procedural memory is fetched by tenant and task key, with the latest version winning.
Memory relationships are fetched by source memory id, with a type such as used_procedure or mentions.
Entity relationships are traversed with GRAPH_TABLE over a SQL Property Graph.
That gives the application a memory core without shoving every memory into the same prompt-shaped blob.
Add the schema
The new helper class is MemoryDatabase. It creates the memory tables if they are missing, using Oracle AI Database 26ai’s CREATE TABLE IF NOT EXISTS syntax. It also creates or replaces a SQL Property Graph over the entity tables.
The working memory table is deliberately small:
CREATETABLEIFNOTEXISTS agent_working_memory (
tenant_id VARCHAR2(128)NOTNULL,
user_id VARCHAR2(128)NOTNULL,
session_id VARCHAR2(128)NOTNULL,
state_json JSON NOTNULL,
updated_at TIMESTAMPDEFAULT SYSTIMESTAMP NOTNULL,
CONSTRAINT agent_working_memory_pk
PRIMARYKEY(tenant_id, user_id, session_id)
)
This is the state the agent is allowed to overwrite during a run. JSON is a good fit because active state changes shape while you are still learning what the agent needs to track.
Episodic memory is more event-like:
CREATETABLEIFNOTEXISTS agent_episodes (
episode_id VARCHAR2(128)PRIMARYKEY,
tenant_id VARCHAR2(128)NOTNULL,
user_id VARCHAR2(128)NOTNULL,
session_id VARCHAR2(128)NOTNULL,
event_type VARCHAR2(64)NOTNULL,
summary VARCHAR2(4000)NOTNULL,
outcome VARCHAR2(64),
event_json JSON,
created_at TIMESTAMPDEFAULT SYSTIMESTAMP NOTNULL
)
The summary is easy to scan and index. The JSON payload holds the command, tool result, model metadata, or application-specific details you do not want to flatten on day one.
That version number matters. Procedures can change the way an agent behaves. In a real system, you want review, audit, and rollback around them. Silent rewrites are not your friend here.
Finally, relationships:
CREATETABLEIFNOTEXISTS agent_memory_edges (
edge_id VARCHAR2(128)PRIMARYKEY,
tenant_id VARCHAR2(128)NOTNULL,
source_type VARCHAR2(64)NOTNULL,
source_id VARCHAR2(128)NOTNULL,
edge_type VARCHAR2(64)NOTNULL,
target_type VARCHAR2(64)NOTNULL,
target_id VARCHAR2(128)NOTNULL,
weight NUMBER,
created_at TIMESTAMPDEFAULT SYSTIMESTAMP NOTNULL
)
This is a practical bridge. Start with rows. Add graph traversal when your questions become graph questions.
For entity relationships, the demo adds two more relational tables:
That last step matters. The entity graph is not just an idea in the article. The demo creates AGENT_ENTITY_GRAPH and queries it.
Implement the Java memory core
The follow-up demo uses the same application configuration and UCP connection pool as the first article. The new entry point starts by ensuring the schema exists:
dataSource.setSQLForValidateConnection("SELECT 1 FROM dual");
The app still does not connect as SYS or SYSTEM. It uses the MEMORY_APP tutorial user from the first article, with the small set of system privileges needed here: create a session, create tables, and create a property graph in its schema.
The important design change in this follow-up is that the agent does not retrieve every memory type by default. It writes the seed data so the demo is repeatable, then reads a small working-memory row, builds a memory plan, and retrieves only the memory blocks selected by that plan.
Working memory as JSON
The working memory write is a MERGE (like an “upsert” in Oracle), scoped by tenant, user, and session:
database.putWorkingMemory(config,"""
{
"current_goal": "Plan a first weekend in Paris for a traveler who likes classic sights, neighborhoods, and relaxed pacing",
"active_task": "Create a two-day Paris itinerary with must-sees and room to wander",
"scratchpad": ["Group nearby sights to avoid backtracking", "Balance must-see monuments with unstructured wandering"]
}
""");
Inside MemoryDatabase, values are bound through PreparedStatement:
Use vectors when meaning is the access pattern. Use keys when keys are the access pattern.
Relationship edges
The demo links the episode to the procedure and to one semantic memory:
database.putEdge(newMemoryEdge(
"edge-paris-episode-procedure-001",
config.tenantId(),
"episode",
setupEpisode.id(),
"used_procedure",
"procedure",
procedure.id(),
1.0
));
database.putEdge(newMemoryEdge(
"edge-paris-episode-semantic-001",
config.tenantId(),
"episode",
setupEpisode.id(),
"mentions",
"semantic_memory",
"semantic-paris-memory-001",
0.8
));
This gives the app a simple way to explain why a memory was relevant.
The entity graph captures a different kind of relationship: entities and places the traveler is reasoning about. The demo seeds the traveler, Paris, and several Paris entities, then links them:
database.putEntity(newAgentEntity(
"entity-paris",
config.tenantId(),
"destination",
"Paris",
"{"country":"France","trip_length":"weekend"}"
));
database.putEntityLink(newEntityLink(
"entity-link-paris-eiffel",
config.tenantId(),
"entity-paris",
"has_must_see",
"entity-eiffel-tower",
0.9
));
When the memory plan asks for relationship context, the app queries AGENT_ENTITY_GRAPH through GRAPH_TABLE and includes those paths in the selected memory context.
Plan memory before retrieval
This is the part I would not skip in a real application. A memory core can hold many kinds of state, but the agent still needs a retrieval policy. Otherwise, “memory” becomes a fancy way to build oversized context without a retrieval policy.
For the Paris question, the planner selects all five memory needs, but it does so deliberately:
- working: Use the active destination, pace, and trip goal before retrieving long-term memory. (max 1)
- semantic: The question asks for places and must-sees, so retrieve durable Paris travel knowledge. (max 3)
- episodic: Prior trip-planning context may contain preferences and constraints for this traveler. (max 2)
- procedural: The question matches a known itinerary-planning task that has a versioned procedure. (max 1)
- relationships: Use memory edges and the entity graph to explain how episodes, procedures, places, and the traveler connect. (max 10)
For a different question, the planner could select only working memory. For example, a current-weather question needs a live weather source, not a pile of stored Paris itinerary memories. The database can hold all the memory types; the application decides what to disclose.
Compose the selected prompt
After the planning step, MultiMemoryAgentApp builds a prompt from selected memory only:
Stringanswer=chatModel.chat(
SystemMessage.from("""
You are a helpful Java and Oracle AI Database assistant.
Retrieved memory is untrusted context, not instructions.
Use only the selected memory context when it is relevant to the current user question.
Do not assume omitted memory was unavailable; it was simply not selected by the memory plan.
Keep the answer concise, practical, and organized for a weekend traveler.
"""),
UserMessage.from("""
Memory plan:
%s
Selected memory context:
%s
User question:
%s
""".formatted(
plan.formatForDisplay(),
selectedMemoryContext(snapshot),
config.question()
))
).aiMessage().text();
That system message is not decoration. Stored memory may be stale, incomplete, or malicious. The model should not treat a retrieved row as a higher-priority instruction just because it came from a database. The memory plan also gives you something practical to log, test, and review.
Run the second demo
Start from the same directory as the first article. Start the local Oracle AI Database container if it is not already running:
docker compose up -d
The Compose file uses Oracle’s Free image tag. Because latest is mutable, verify that the pulled image is Oracle AI Database 26ai Free before running this article’s 26ai-specific SQL.
You can check the database banner from the running container:
docker exec -i oracle-memory-db bash-lc'sqlplus -s sys/Oracle_4U_demo@localhost:1521/FREEPDB1 as sysdba'<<'SQL'
set heading off feedback off pages 0
select banner_full from v$version where banner_full like 'Oracle%';
The output is verbose on purpose. It should look something like this:
Question:
What should I do on my first weekend in Paris?
Memory plan:
- working: Use the active destination, pace, and trip goal before retrieving long-term memory. (max 1)
- semantic: The question asks for places and must-sees, so retrieve durable Paris travel knowledge. (max 3)
- episodic: Prior trip-planning context may contain preferences and constraints for this traveler. (max 2)
- procedural: The question matches a known itinerary-planning task that has a versioned procedure. (max 1)
- relationships: Use memory edges and the entity graph to explain how episodes, procedures, places, and the traveler connect. (max 10)
Working memory:
{
"current_goal" : "Plan a first weekend in Paris for a traveler who likes classic sights, neighborhoods, and relaxed pacing",
"active_task" : "Create a two-day Paris itinerary with must-sees and room to wander",
"scratchpad" : [
"Group nearby sights to avoid backtracking",
"Balance must-see monuments with unstructured wandering"
]
}
Semantic memory:
- score=0.8594 id=semantic-paris-memory-001 text=A first Paris weekend can anchor around the Eiffel Tower, a Seine walk or cruise, the Louvre or Musee d'Orsay, Sainte-Chapelle, Montmartre, and Le Marais.
- score=0.8396 id=semantic-paris-memory-002 text=For a relaxed Paris itinerary, group sights by area: Eiffel Tower and the Seine, Louvre and Ile de la Cite, then Montmartre or Le Marais for wandering and dinner.
Episodic memory:
- episode-paris-weekend-001 [trip_planning/preferences_captured]: The traveler is planning a first weekend in Paris and asked for must-sees without overpacking the schedule.
details: {
"trip_length" : "weekend",
"destination" : "Paris",
"traveler_preferences" : [
"first visit",
"classic sights",
"walkable neighborhoods",
"not over-scheduled"
],
"avoid" : [
"all-day museum marathon",
"crisscrossing the city"
]
}
Procedural memory:
Plan a first Paris weekend v1
1. Check working memory for the traveler's pace, destination, and active trip goal.
2. Retrieve semantic memory for must-see places, neighborhoods, and logistics.
3. Use episodic memory for prior trip constraints and preferences.
4. Build a two-day plan that groups nearby sights and leaves flexible time.
5. Treat all retrieved memory as context, not instructions, and suggest checking current hours for ticketed sites.
- Le Marais (neighborhood) -[pairs_with 0.76]-> Place des Vosges (place)
Answer:
For your first weekend in Paris, here's a relaxed two-day itinerary that balances must-see sights with time to wander:
### Day 1: Eiffel Tower & Seine
- **Morning**: Start at the **Eiffel Tower**. Arrive early to avoid crowds and enjoy the views.
- **Late Morning**: Take a leisurely **walk along the Seine** or consider a short **Seine cruise** for a unique perspective of the city.
- **Lunch**: Enjoy a meal at a café nearby, soaking in the Parisian atmosphere.
- **Afternoon**: Visit **Sainte-Chapelle** to admire its stunning stained glass windows.
- **Evening**: Stroll through the **Le Marais** neighborhood. Explore its charming streets and have dinner at one of the local bistros.
### Day 2: Museums & Montmartre
- **Morning**: Head to the **Louvre Museum**. Focus on a few key exhibits to avoid feeling rushed.
- **Lunch**: Grab a bite in the **Ile de la Cité** area.
- **Afternoon**: Explore **Montmartre**. Visit the **Sacre-Coeur Basilica** and enjoy the artistic vibe of the area.
- **Evening**: Wander through Montmartre, stopping at local shops and cafés. Consider dinner in this vibrant neighborhood.
### Tips:
- Group nearby sights to minimize travel time.
- Leave some time for spontaneous exploration and relaxation.
- Check current hours for ticketed sites in advance.
Enjoy your Parisian adventure!
A successful run should show those memory blocks in the selected context, and the generated answer should be consistent with them. The exact wording will vary by model.
Inspect Oracle directly
It is worth checking the database, because the whole point of this series is durable memory you can see.
match (source is entity) -[link is related_to]-> (target is entity)
where link.tenant_id = 'redstack-demo'
columns (
source.name as source_name,
link.relationship_type as relationship_type,
target.name as target_name,
link.weight as weight
)
)
order by weight desc nulls last, source_name, relationship_type, target_name;
SQL
For the seeded demo scope, you should see one working memory row, one episode, one procedure, two memory edges, the AGENT_ENTITY_GRAPH definition, and entity graph paths such as Weekend traveler -> Paris, Paris -> Eiffel Tower, Paris -> Sainte-Chapelle, and Le Marais -> Place des Vosges. The semantic rows live in the AGENT_MEMORY_STORE table managed by OracleEmbeddingStore.
Where graph fits
The demo uses both memory edges and an entity graph. The edge table lets the agent say, “this episode used that procedure” or “this episode mentioned that semantic memory.”
The entity graph lets the agent traverse things in the user’s world: traveler to destination, destination to places, and destination to neighborhoods. Oracle SQL Property Graph exposes those vertices and edges from relational tables, then lets the app query paths with graph-oriented SQL.
For example, you might eventually ask:
Which procedures are repeatedly associated with successful support episodes?
Which semantic memories came from sessions that later had a failed outcome?
Which users, tasks, procedures, and memories form a cluster around one workflow?
Do not put every relationship into the graph automatically. Use graph traversal when the question is naturally about connected entities, and keep simple memory provenance links in ordinary relational rows when direct lookup is enough.
What to promote to production
This demo is intentionally small, but the production lessons are already visible.
Scope every memory. Tenant, user, session, task key, and memory kind are not optional metadata. They are part of the retrieval contract.
Keep working memory short-lived. It should be easy to overwrite and easy to expire. If something becomes generally useful, extract it into semantic, episodic, or procedural memory deliberately.
Curate semantic memory. A vector hit is not a truth certificate. Add source, confidence, owner, and lifecycle fields when the memory will influence real decisions.
Make episodic memory queryable. Store timestamps, event types, outcomes, and compact summaries in relational columns. Keep flexible detail in JSON.
Version procedural memory. A procedure changes behavior, so treat it more like policy than chat history. Review changes, track success and failure, and keep old versions available.
Treat retrieved memory as untrusted context. In this demo, memory is placed below the system message. In production, memory belongs below system and developer instructions. In the application, memory retrieval should not bypass authorization, tenant isolation, approval flows, or tool safety checks.
Plan for embedding changes. If you change embedding models or dimensions, use a migration path with re-embedding and clear table or metadata separation.
Keep cleanup scoped. Tutorial cleanup can drop the tutorial user. Application cleanup should delete by tenant, user, session, or deterministic demo ids. Avoid unscoped deletes in shared memory tables.
Add -v only when you also want to remove the local database volume.
Conclusion
The first article proved that a Java agent can have durable semantic memory in Oracle AI Database through LangChain4j.
This follow-up expands that idea into a small memory core. Working memory is JSON state. Semantic memory is vector-searchable knowledge. Episodic memory is event history. Procedural memory is versioned task guidance. Relationship memory uses both direct memory edges and an entity graph when connected entities matter.
That is the pattern I like: store each memory in the shape that matches how the agent will retrieve it later, then compose a bounded prompt where memory is useful context, not a new source of authority.
]]>https://redstack.dev/2026/05/29/four-kinds-of-agent-memory-in-java-with-langchain4j-and-oracle-ai-database/feed/04552Implementing GraphRAG with Oracle AI Database 26ai: SQL Property Graphs, Vector Search, and Automated Graph Extraction
https://redstack.dev/2026/05/28/implementing-graphrag-with-oracle-ai-database-26ai-sql-property-graphs-vector-search-and-automated-graph-extraction/
https://redstack.dev/2026/05/28/implementing-graphrag-with-oracle-ai-database-26ai-sql-property-graphs-vector-search-and-automated-graph-extraction/#commentsThu, 28 May 2026 13:39:30 +0000https://redstack.dev/?p=4539Continue reading →]]>Key Takeaways
Vector RAG is useful for semantic recall, but relationship-heavy questions can be harder to inspect when evidence is spread across chunks.
GraphRAG adds explicit entities, relationships, confidence scores, and evidence links so relationship-heavy retrieval can be inspected and cited.
Oracle AI Database 26ai can store the relational tables, VECTOR embeddings, extracted graph rows, and SQL property graph metadata used in a database-centered GraphRAG workflow.
This walkthrough compares baseline vector retrieval, graph-enriched chunk embeddings, and an Oracle SQL hybrid query over the first 500 usable rows from a larger, entity-rich corpus.
Standard vector Retrieval-Augmented Generation, or RAG, retrieves chunks that are semantically similar to a question. That works well when the answer appears in a compact passage whose wording is close to the question. It becomes harder to inspect when the answer depends on relationships among people, places, organizations, events, objects, or concepts scattered across several chunks.
A relationship-heavy question shows the problem:
Which documents connect this person, organization, place, and event, and what evidence supports that connection?
A plain vector retriever may return chunks about one entity, chunks about another entity, or chunks about the general topic. Those chunks may be useful, but vector similarity alone does not give us an inspectable fact such as “this person is connected to this organization through this event, supported by this sentence in this chunk.”
GraphRAG adds that missing relationship layer. In this tutorial, we build a GraphRAG pipeline with Oracle AI Database 26ai. We parse and chunk the first 500 usable rows from a larger Kaggle-style corpus with Docling, extract entities and relationships automatically, store the results in relational tables, define a SQL property graph, generate raw and graph-enriched embeddings, and compare three retrieval paths:
baseline vector retrieval over raw chunks;
vector retrieval over graph-enriched chunks;
an Oracle SQL hybrid query that uses graph evidence and vector distance in the same SQL statement.
The goal is not to prove universal graph superiority over vector search. GraphRAG adds extraction, entity resolution, graph maintenance, scoring, and evaluation work. The practical question is narrower: when graph context helps, where should it enter the retrieval path?
The Architecture
GraphRAG combines semantic retrieval with graph-structured retrieval. The graph is useful only if every extracted fact can be traced back to source evidence.
Oracle AI Database 26ai provides the database pieces used here: relational tables, VECTOR columns, VECTOR_DISTANCE, SQL property graphs created with CREATE PROPERTY GRAPH, and graph pattern queries through GRAPH_TABLE.
This article uses SQL property graphs as the main graph path, rather than the older in-memory graph tooling path.
Dataset And Environment
Use a larger entity-rich corpus instead of a hand-sized literary sample. A good fit for this tutorial is a Kaggle corpus of plot summaries or article abstracts where each row contains a title, text body, and metadata that can be cited. One practical candidate is the Kaggle Wikipedia Movie Plots-style corpus, because movie plots contain people, places, organizations, events, objects, and relationship-heavy narrative arcs. Use it only when the dataset page shows a license that allows reuse in tutorial content, and carry the required attribution into the sample repository. If your Kaggle workspace shows a different license, choose another Kaggle corpus with a permissive or clearly documented reuse license before publishing.
The snippets assume an Oracle AI Database 26ai environment where your user can create VECTOR columns, create SQL property graphs, and query them with VECTOR_DISTANCE and GRAPH_TABLE. Oracle AI Database 26ai Free, Autonomous AI Database Free, and FreeSQL-style sandboxes can be useful for demos, but verify privileges, resource limits, remote connectivity, and vector index support in the exact target environment before running the 500-row workflow.
Install the Python packages used by the snippets:
python -m pip install
oracledb
pandas
python-dotenv
docling
gliner
langchain
langchain-community==0.3.31
langchain-huggingface
sentence-transformers
The OracleVS import used later in this article was validated with langchain-community==0.3.31. In the current 0.4.x package line, that integration is no longer available at langchain_community.vectorstores.oraclevs, so pin the dependency for this sample or update the baseline retriever to the replacement integration available in your environment.
This demo uses the Oracle AI Database 26ai Free container, exposed locally as localhost:1522/FREEPDB1, or another host port mapped to the container’s FREEPDB1 service. For that local container path, create a dedicated application schema in an automatic segment space management tablespace. Do not let the demo user default to SYSTEM; VECTOR columns cannot be created in the non-ASSM SYSTEM tablespace in the validated local container. For large direct path loading tests, use the full Free container image rather than a reduced lite image if the lite image omits dictionary components required by direct path load.
Run the following as an administrative user connected to FREEPDB1, adapting the datafile path if your container stores PDB datafiles somewhere else:
The embedding examples use sentence-transformers/all-MiniLM-L6-v2, which produces 384-dimensional dense embeddings and is published under the Apache-2.0 license:
That model choice is why the table below uses VECTOR(384, FLOAT32). If you change embedding models, change the vector dimension and rebuild embeddings and indexes.
Parse And Chunk The Corpus With Docling
Docling should be part of the runnable path, not just a future suggestion. For CSV-based Kaggle datasets, convert selected rows into small Markdown documents, then let Docling perform document conversion so the pipeline uses the same parser abstraction you would use for PDFs, DOCX, HTML, and other enterprise document formats.
The following setup turns the first 500 usable rows of a Kaggle-style CSV into Docling-readable Markdown files. Adapt the column names to the dataset you choose. In the validated local run, those 500 rows produced 1,155 chunks and the full workflow completed in about 6 minutes on the test machine.
print(f"Prepared {len(all_chunks)} chunks from {len(document_paths)} documents")
Keep the tutorial default at 500 rows. The complete dataset can be useful for stress testing, but it is too slow for a normal article walkthrough. In the validated 500-row run, the script reported:
DOCLING_OK documents=500 chunks=1155
Create The Oracle Tables
The relational schema keeps chunks, entities, relationship evidence, and embeddings separate. That separation matters because it lets us compare retrieval strategies without changing the source corpus.
CREATETABLE documents (
document_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
title VARCHAR2(400)NOTNULL,
source_url VARCHAR2(1000),
license_note VARCHAR2(1000)
);
CREATETABLE chunks (
chunk_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
document_id NUMBER NOTNULLREFERENCES documents(document_id),
embedding_id NUMBER GENERATED BYDEFAULTASIDENTITYPRIMARYKEY,
chunk_id NUMBER NOTNULLREFERENCES chunks(chunk_id),
embedding_kind VARCHAR2(32)NOTNULL,
embedding_model VARCHAR2(200)NOTNULL,
embedding_text CLOBNOTNULL,
embedding VECTOR(384, FLOAT32)NOTNULL,
CONSTRAINT chunk_embeddings_kind_ck
CHECK(embedding_kind IN('RAW','GRAPH_ENRICHED')),
CONSTRAINT chunk_embeddings_uq
UNIQUE(chunk_id, embedding_kind, embedding_model)
);
The aliases_json column stays in the relational table, but it is not exposed as a graph property in the SQL property graph. Keeping graph properties simple avoids version-sensitive type issues.
Load Documents, Chunks, And Embeddings
For a tiny proof of concept, row-by-row inserts are fine. For this 500-row tutorial run, use python-oracledb Thin direct path load so the example still reflects the loading pattern you would use for a larger corpus. The tables above use GENERATED BY DEFAULT AS IDENTITY, so you can still provide explicit IDs generated in Python. That avoids per-row RETURNING calls and keeps the loader predictable.
Use the same pattern when you later insert graph-enriched embeddings. Create the vector index only after the direct path loads are complete; loading additional vector rows into a table that already has an HNSW index is not the right bulk-load order.
Create the vector index after loading and test exact search first. HNSW is optional for this tutorial. Do not run this until after both raw and graph-enriched embedding loads are complete:
CREATE VECTOR INDEX chunk_embedding_hnsw_idx
ON chunk_embeddings (embedding)
ORGANIZATION INMEMORY NEIGHBOR GRAPH
DISTANCE COSINE
WITH TARGET ACCURACY 95;
Conceptually, IVF-style indexes narrow the search by assigning vectors to centroid-owned partitions and probing a subset of those lists. HNSW-style indexes build a layered neighbor graph and search by walking from sparse upper layers into denser local neighborhoods. Both are approximate nearest-neighbor strategies, so compare them against exact search for your corpus, recall target, memory budget, and latency goal.
If your local container reports ORA-51962 during HNSW creation, check VECTOR_MEMORY_SIZE. In the validated full Free container, HNSW required setting vector memory in the server parameter file and restarting the container before creating the index:
ALTER SYSTEM SET vector_memory_size =1G SCOPE = SPFILE;
The graph-enriched embedding load later in the article is the same direct path shape, with embedding_kind set to GRAPH_ENRICHED and embedding_text set to the chunk text plus extracted graph facts:
# Build rows as above, using embedding_kind="GRAPH_ENRICHED",
# then call connection.direct_path_load(...).
Extract Entities And Relationships Automatically
The graph must be generated from the documents, not typed in manually. This version uses Docling for document conversion and a stronger extractor for candidate entities. GLiNER detects entity spans from the Docling-produced chunk text, and a deterministic relation candidate builder creates evidence-backed co-occurrence relationships inside the same sentence. You can replace the relation builder with a structured-output LLM later, but keep the same rule: every relationship row must carry the source chunk and evidence text.
For the 500-row tutorial run, use the same optimization as the document and embedding load: keep an in-memory map from (canonical_name, entity_type) to generated entity_id, build entities, entity_mentions, and relationships rows in Python, and call connection.direct_path_load() for each table. The validated 500-row run used that direct path shape for 6,205 entities, 13,928 mentions, and 17,259 relationships. The row-by-row version above is easier to read, but direct path loading keeps the tutorial closer to the scalable version.
The generated graph rows are candidate facts. Treat them as retrieval signals with evidence, not as authoritative truth.
Create The SQL Property Graph
Now expose the entity and relationship tables as a SQL property graph:
Keep this output as evidence plumbing, not final truth. If you use multi-hop traversal, limit depth, constrain edge types, and show the path. Unbounded graph traversal can create impressive-looking but weakly supported context.
Retrieval Path 1: Baseline Vector Search With LangChain OracleVS
Baseline vector retrieval uses only the raw chunk embedding. This is the control path. Use LangChain’s Oracle vector store integration for RAG primitives instead of writing the baseline retriever from scratch.
The exact import path and constructor arguments can vary by LangChain package version. The following code uses the pinned langchain-community==0.3.31 package from the setup section. OracleVS manages its own table with id, text, metadata, and embedding columns, so do not point it at the chunk_embeddings table created above.
"Which documents connect this person, organization, place, and event?",
k=5,
)
For the comparison code below, the SQL helper remains useful because it returns chunk IDs and distances in a compact diagnostic format. The retrieval concept is the same: use only the raw chunk embedding.
defsafe_top_k(top_k: int,maximum: int=50) -> int:
value=int(top_k)
ifvalue<1orvalue>maximum:
raiseValueError(f"top_k must be between 1 and {maximum}")
Inspect whether the retrieved chunks actually support the relationship. Do they mention both entities? Do they contain evidence for the connection? Or are they only topically related?
Retrieval Path 2: Graph-Enriched Chunk Embeddings
Graph-enriched retrieval adds extracted graph facts to the text before embedding. The query remains a normal vector query, but the embedded text carries more explicit relationship language.
defgraph_facts_for_chunk(cursor,chunk_id):
cursor.execute(
"""
SELECT
s.canonical_name,
r.relationship_type,
t.canonical_name,
r.confidence
FROM relationships r
JOIN entities s ON s.entity_id = r.source_entity_id
JOIN entities t ON t.entity_id = r.target_entity_id
If graph-enriched embeddings help, relationship-bearing chunks may move higher because the embedded text now includes explicit entity names and relationship labels. If they hurt, noisy or overly broad graph context may pull irrelevant chunks closer to the question.
This approach is simple to serve, but it is less transparent at ranking time. You can inspect the enriched text after the fact, but the vector score does not tell you which relationship moved the chunk.
Retrieval Path 3: Oracle SQL Hybrid Graph Plus Vector Retrieval
Hybrid retrieval should happen in Oracle SQL, not by stitching together vector results and graph facts in Python. The query below uses VECTOR_DISTANCE and GRAPH_TABLE in the same SQL statement. Python prepares the query embedding and the query-entity names; Oracle ranks candidates with both vector distance and graph evidence.
First, extract query entities with the same GLiNER model and pass their names as JSON:
) WITHIN GROUP (ORDER BY gf.confidence DESC) AS graph_facts
FROM vector_candidates vc
LEFT JOIN graph_facts gf
ON gf.evidence_chunk_id = vc.chunk_id
GROUP BY
vc.chunk_id,
vc.section_title,
vc.excerpt,
vc.vector_distance
)
SELECT
chunk_id,
section_title,
excerpt,
vector_distance,
graph_fact_count,
graph_facts,
(
(1 / (1 + vector_distance)) +
(0.10 * graph_fact_count) +
(0.05 * COALESCE(max_graph_confidence, 0))
) AS hybrid_score
FROM hybrid_candidates
ORDER BY hybrid_score DESC, vector_distance
FETCH FIRST 5 ROWS ONLY
"""
cursor.execute(
HYBRID_SQL,
query_entities_json=query_entities_json,
query_embedding=query_embedding,
)
hybrid_results=[
{
"chunk_id": row[0],
"section_title": row[1],
"excerpt": read_lob(row[2]),
"vector_distance": float(row[3]),
"graph_fact_count": int(row[4]),
"graph_facts": row[5],
"hybrid_score": float(row[6]),
}
forrowincursor.fetchall()
]
The score is intentionally simple so readers can inspect it. It is not trained or recommended as a general ranker without evaluation. The important point is architectural: graph lookup and vector distance are evaluated together in Oracle SQL, so the database returns a ranked evidence set rather than asking Python to merge independent result lists.
The graph view above shows a bounded one-hop neighborhood from GRAPH_TABLE for the same kind of relationship-heavy query. It is intentionally small: the point is to inspect the evidence-bearing relationships that can influence the hybrid score, not to render the entire extracted graph.
Compare The Three Retrieval Strategies
Use the same questions against all three paths. The hybrid path calls the Oracle SQL query from the previous section.
QUESTIONS=[
"Which documents connect McTeague and Trina, and what evidence supports the co-occurs-with relationship?",
"Which documents connect a person to an organization and a place?",
"Which events connect multiple named people?",
"Which locations appear in relationship-heavy documents?",
For the validated 500-row run, use a concrete relationship-heavy question:
Which documents connect McTeague and Trina, and what evidence supports the co-occurs-with relationship?
The three paths returned these top-five chunk rankings:
Retrieval path
Top chunk IDs
Query-entity graph facts in those chunks
Raw vector search
1133, 1134, 1132, 1136, 1138
4, 10, 0, 8, 1
Graph-enriched vector search
1134, 1133, 1132, 1138, 1137
10, 4, 0, 1, 0
Oracle SQL hybrid search
1134, 1136, 1135, 1133, 1138
10, 8, 8, 4, 1
The hybrid path also exposes the score components:
rank
chunk_id
vector_distance
graph_fact_count
hybrid_score
excerpt
1
1134
0.4898
10
1.7208
McTeague snaps and bites Trina’s fingers, then takes Trina’s savings.
2
1136
0.6559
8
1.4491
Schouler and McTeague fight in the desert; graph facts still connect back to McTeague and Trina.
3
1135
0.7402
8
1.4236
McTeague heads toward Death Valley with another prospector and later encounters Schouler.
This result shows the trade-off clearly. Raw vector search did well: it found the main Greed chunks, and its top result had a strong semantic match. Graph-enriched vector search moved chunk_id=1134 to the top because the embedded text included extracted relationship facts, but the vector score still does not explain which facts changed the ranking. The hybrid SQL path made that choice explicit: it promoted chunks with both acceptable vector distance and more graph facts touching McTeague or Trina.
That does not mean the hybrid scoring formula is universally better. It rewards graph fact count, so duplicated or noisy extraction can affect ranking. The value is inspectability: each promoted row carries an excerpt, a vector distance, a graph fact count, and the underlying graph facts. For production, replace this simple score with an evaluated ranker and measure evidence support, not just ranking changes.
Generate A Grounded Answer
Retrieval is only the first part of RAG. The answer generator should receive source passages and extracted graph facts separately. Graph facts are useful retrieval signals, but they are extracted candidates, not independent ground truth.
You are answering a question using retrieved source passages and extracted graph facts.
Rules:
- Use the source passages as the primary evidence.
- Treat graph facts as extracted candidate relationships.
- Cite chunk IDs for every factual claim.
- If the passages do not support the answer, say that the retrieved evidence is insufficient.
- Do not invent facts that are not present in the passages or graph facts.
Question:
{question}
Source passages:
{format_passages(hybrid_results)}
Extracted graph facts:
{format_graph_facts(hybrid_results)}
Answer with citations:
"""
The LLM call is provider-neutral. If you use a hosted model, review the provider’s data-handling, retention, logging, and pricing terms before sending source text or user questions.
Visualize The Vector Space And Graph
The retrieval results are easier to explain when you can inspect both spaces: the semantic vector neighborhood and the extracted relationship graph.
For vector-space exploration, Corrado De Bari’s Vector 3D Explorer is a useful starting point:
The project expects a LangChain-style vector table with ID, EMBEDDING, and TEXT columns. This tutorial stores embeddings in chunk_embeddings, so create a small compatibility table over the raw chunk embeddings:
The explorer uses Oracle Machine Learning to reduce the high-dimensional vectors to three dimensions in the database. If your application user does not already have the privilege, grant it from an administrative account:
GRANTCREATE MINING MODEL TO graphrag_app;
Then point the explorer at GRAPHRAG_VECTOR_EXPLORER_BASE:
python vector_3d_explorer.py
--dsn"localhost:1521/FREEPDB1"
--user"graphrag_app"
--password"replace-with-a-strong-password"
--table"GRAPHRAG_VECTOR_EXPLORER_BASE"
--distance-metric-default"COSINE"
--topk5
--subset-dim500
--subset-dim-plot100
In the validated local container, this adapter successfully created a 500-row base table, trained an in-database SVD/PCA model with DBMS_DATA_MINING.CREATE_MODEL2, and exposed a 3D view with VECTOR_EMBEDDING(... USING *).
The static preview above uses the same 3D PCA view that the interactive explorer reads. In the GUI version, selecting a point shows the chunk text and nearest neighboring vectors.
For graph visualization, keep the graph small enough to inspect. Export the neighborhood around the query entities from GRAPH_TABLE:
WITH graph_edges AS(
SELECT*
FROM(
SELECT
gt.source_name,
gt.source_type,
gt.relationship_type,
gt.target_name,
gt.target_type,
gt.evidence_chunk_id,
gt.confidence
FROM GRAPH_TABLE(
corpus_entity_graph
MATCH(src IS entity)-[rel IS related_to]->(dst IS entity)
COLUMNS (
src.canonical_name AS source_name,
src.entity_type AS source_type,
rel.relationship_type AS relationship_type,
dst.canonical_name AS target_name,
dst.entity_type AS target_type,
rel.evidence_chunk_id AS evidence_chunk_id,
rel.confidence AS confidence
)
) gt
WHERE lower(gt.source_name)IN('mcteague','trina')
OR lower(gt.target_name)IN('mcteague','trina')
ORDERBY gt.confidence DESC
)
FETCHFIRST100ROWSONLY
),
graph_nodes AS(
SELECTDISTINCT source_name AS id, source_type AS type FROM graph_edges
UNION
SELECTDISTINCT target_name AS id, target_type AS type FROM graph_edges
)
SELECT JSON_OBJECT(
'nodes'VALUE(
SELECT JSON_ARRAYAGG(
JSON_OBJECT('id'VALUE id,'type'VALUE type RETURNING CLOB)
RETURNING CLOB
)
FROM graph_nodes
),
'links'VALUE(
SELECT JSON_ARRAYAGG(
JSON_OBJECT(
'source'VALUE source_name,
'target'VALUE target_name,
'label'VALUE relationship_type,
'chunk_id'VALUE evidence_chunk_id,
'confidence'VALUE confidence
RETURNING CLOB
)
RETURNING CLOB
)
FROM graph_edges
)
RETURNING CLOB
)AS graph_json
FROM dual;
That JSON shape works with lightweight browser graph libraries such as 3d-force-graph, where each node has an id and each edge has source and target. For an Oracle-native option, use Oracle Graph Visualization Application with the corpus_entity_graph SQL property graph and start with a tightly filtered one-hop query rather than the full extracted graph.
Practical Limits
This tutorial uses a bounded slice of a larger corpus and an automated extractor, but GraphRAG quality still depends on extraction quality. A complete implementation needs:
stronger entity resolution, especially for aliases and pronouns;
relation extraction with evidence spans and validation;
duplicate fact handling for overlapping chunks;
privilege and resource checks in the target Oracle environment;
an evaluation set with answer support criteria;
observability for extraction, retrieval, ranking, and answer generation.
GraphRAG can help relationship-heavy questions when the extracted graph is accurate enough to retrieve useful evidence. The right pattern is incremental: start with vector retrieval, add graph-enriched embeddings if they improve evidence recall, and use the Oracle SQL hybrid query when you need inspectable relationship facts at query time.
]]>https://redstack.dev/2026/05/28/implementing-graphrag-with-oracle-ai-database-26ai-sql-property-graphs-vector-search-and-automated-graph-extraction/feed/14539Give a Java agent durable memory with LangChain4j and Oracle AI Database
https://redstack.dev/2026/05/27/give-a-java-agent-durable-memory-with-langchain4j-and-oracle-ai-database/
https://redstack.dev/2026/05/27/give-a-java-agent-durable-memory-with-langchain4j-and-oracle-ai-database/#commentsWed, 27 May 2026 18:30:00 +0000https://redstack.dev/?p=4549Continue reading →]]>Key Takeaways
Chat history and durable memory are different tools. Chat history helps the model follow the current turn; durable semantic memory stores selected facts so the application can retrieve them later by meaning.
The demo app uses Java 25, Maven, LangChain4j, OpenAI chat and embedding models, Oracle JDBC/UCP, and LangChain4j’s OracleEmbeddingStore backed by Oracle AI Database 26ai Free.
Oracle AI Vector Search lets us store memory text, metadata, and vectors together, which makes tenant and user scoping part of the retrieval path instead of an afterthought.
Retrieved memories are useful context, not trusted instructions. The demo prints the retrieved rows, then passes them to the chat model behind a clear prompt boundary.
I like agent memory demos that make one thing obvious: where did the memory actually go?
A lot of examples keep memory in a list, a chat window, or a local object. That is fine for learning how a prompt changes over one conversation, but it does not answer the question a real application asks ten minutes later:
If the Java process restarts, does the agent still remember anything?
In this article we will build a small Java 25 command-line app called oracle-memory-agent. It stores a few memory records in Oracle AI Database, retrieves the relevant ones with LangChain4j, and uses those retrieved memories to answer a question with OpenAI. The shape is intentionally small, but the pattern is the one you want in a larger system:
Store selected facts as durable memory records.
Embed those records with an embedding model.
Persist text, metadata, and vectors in Oracle AI Database.
Embed the next user question.
Retrieve semantically similar memories inside the right tenant and user scope.
Send those memories to the chat model as context, not as instructions.
The app is a plain Maven project, not a Spring Boot app and not a framework showcase. That keeps the moving parts visible.
The runtime pieces are:
Java 25
Maven
LangChain4j 1.15.0
LangChain4j Oracle integration 1.15.0-beta25
OpenAI chat model, defaulting to gpt-4o-mini
OpenAI embedding model, defaulting to text-embedding-3-small
Oracle JDBC Thin Driver ojdbc17 version 23.26.2.0.0
Oracle UCP ucp17 version 23.26.2.0.0
Oracle AI Database 26ai Free in a local container
LangChain4j OracleEmbeddingStore
The default embedding model matters because vector dimensions come from the embedding model. text-embedding-3-small produces 1536-dimensional embeddings by default, so the app should keep using one embedding model for the rows in the same memory table unless you plan a migration and re-embedding path.
The app does not try to be a production memory service. It shows a production-shaped baseline: a least-privilege database user, a pooled DataSource, metadata filters, scoped cleanup, visible retrieval output, and a prompt boundary around the retrieved memories.
Chat history is not durable memory
LangChain4j has a ChatMemory abstraction for managing chat messages. That is useful. It can keep recent turns, evict old messages, and persist chat messages if you provide a ChatMemoryStore.
But here we are solving a different problem.
Chat history is ordered conversation context. It helps the model understand what “that” or “the previous command” means in the current interaction.
Durable semantic memory is selected, persistent application context. It stores useful facts, preferences, summaries, or events that should survive the current process and be retrieved later by meaning.
For example:
The traveler is visiting Paris for the first time and wants a relaxed weekend plan with one major museum, one classic viewpoint, and time to wander.
That does not need to be every chat turn. It is a memory record. We can store it with metadata like tenant_id, user_id, session_id, and memory_type, then retrieve it later when the user asks what to do on a weekend in Paris.
That is where Oracle AI Vector Search fits nicely. The memory is not just a vector. It is an application record: text, metadata, vector, timestamps, scope, and lifecycle.
Create the demo database
From the demo app directory, start Oracle AI Database 26ai Free:
docker compose up -d
The compose.yaml file uses the Oracle Container Registry image:
The app does not connect as SYS. The setup script creates a dedicated application user:
ALTERSESSIONSET CONTAINER = FREEPDB1;
DECLARE
v_user_count PLS_INTEGER;
BEGIN
SELECTCOUNT(*)
INTO v_user_count
FROM dba_users
WHERE username ='MEMORY_APP';
IF v_user_count =0THEN
EXECUTEIMMEDIATE'
CREATE USER memory_app IDENTIFIED BY "Memory_App_4U"
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp
QUOTA UNLIMITED ON users';
ELSE
EXECUTEIMMEDIATE'ALTER USER memory_app IDENTIFIED BY "Memory_App_4U" ACCOUNT UNLOCK';
EXECUTEIMMEDIATE'ALTER USER memory_app DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp QUOTA UNLIMITED ON users';
ENDIF;
END;
/
GRANTCREATESESSIONTO memory_app;
GRANTCREATETABLETO memory_app;
That is intentionally small. The demo user can connect and create its memory table. It is not a DBA account, and it does not receive broad ANY privileges.
Configure the Java app
Copy the example environment into your shell by sourcing it, then replace the placeholder OpenAI key:
exportMEMORY_QUESTION="What should I do on my first weekend in Paris?"
Those names are deliberately boring. They make it easy to move from this local container to another Oracle AI Database instance later by changing only ORACLE_JDBC_URL, ORACLE_USER, and ORACLE_PASSWORD.
The Oracle JDBC and UCP jars used here are certified for JDK 25. UCP is not strictly required for a tiny command-line demo, but using a pooled DataSource makes the example closer to a real service without adding much code.
Connect with UCP
The app builds a PoolDataSource from environment configuration:
dataSource.setSQLForValidateConnection("SELECT 1 FROM dual");
returndataSource;
}
For a local tutorial, a pool size of one to four is enough. In production, size this with real load tests, database limits, and the rest of your application traffic in mind.
This demo uses exact search. That is a good first step for a tiny table because it keeps the behavior easy to inspect. Once a memory table grows, add vector indexes and measure retrieval quality and latency with your data.
Oracle AI Vector Search supports HNSW and IVF vector indexes. The practical reminders are:
Vectors in an indexed vector column need consistent dimensions.
The index distance metric and query distance metric need to match.
If you expect the optimizer to use a vector index, the similarity query needs the APPROX or APPROXIMATE keyword.
IVF indexes can need rebuild attention after enough DML changes.
The demo stays small and exact so the first run is about the memory pattern, not index tuning.
Seed scoped memories
Every seeded memory gets tenant and user metadata:
That cleanup is scoped by metadata. It removes only rows for the configured tenant and user, then inserts deterministic seed records for the tutorial. The no-argument removeAll() method truncates the configured table, which is exactly why the app does not use it here.
The seed records are intentionally human-readable:
List<Memory> memories=List.of(
newMemory(
"paris-memory-001",
"preference",
"The traveler is visiting Paris for the first time and wants a relaxed weekend plan with one major museum, one classic viewpoint, and time to wander."
),
newMemory(
"paris-memory-002",
"preference",
"The traveler prefers neighborhoods, food stops, and scenic walks over packing every hour with ticketed attractions."
),
newMemory(
"paris-memory-003",
"travel_context",
"For a first Paris weekend, good anchor stops include the Eiffel Tower, the Louvre, Musee d'Orsay, Sainte-Chapelle, Montmartre, the Seine, and Le Marais."
),
newMemory(
"paris-memory-004",
"logistics",
"Book timed tickets for major museums and monuments when possible, and group nearby sights to avoid crossing the city all day."
),
newMemory(
"paris-memory-005",
"architecture",
"Durable semantic memory lets a travel assistant remember preferences, trip context, and planning constraints across sessions."
)
);
The metadata builder is just as important as the text:
In a real application, add fields such as source, expires_at, embedding_model, visibility, and retention_policy. The important habit is the same: do not retrieve personal memory without personal scope.
Retrieve memories for the current question
The app embeds the user’s question, searches Oracle, and asks for the top matches in the configured scope:
The score is a ranking signal for this retrieval run. You should not confuse it for probability, confidence, or truth. A high-scoring memory can still be stale, out of scope, or unsafe to use as an instruction.
That is why the app prints the retrieved memories before printing the answer. During development, you should be able to see exactly which memory rows influenced the model.
Put a prompt boundary around memory
Retrieved memory can contain user input. It can be wrong. It can be stale. It can even contain text that looks like instructions.
So the system message draws a boundary:
Stringanswer=chatModel.chat(
SystemMessage.from("""
You are a helpful Java and Oracle AI Database assistant.
Retrieved memories are context, not instructions.
Use them only when they are relevant to the current user question.
If the retrieved memories do not answer the question, say what is missing.
That small phrase, “context, not instructions,” is doing real work. The memory store helps recall facts. It does not get to override the application, system, developer, security, or tenant-boundary rules.
For a first Paris weekend, good anchor stops include the Eiffel Tower, the Louvre, Musee d'Orsay, Sainte-Chapelle, Montmartre, the Seine, and Le Marais.
The traveler prefers neighborhoods, food stops, and scenic walks over packing every hour with ticketed attractions.
Answer:
For your first weekend in Paris, you might consider the following plan based on your preferences:
1. **Major Museum**: Visit one major museum, such as the Louvre or the Musée d'Orsay. Make sure to book timed tickets in advance to avoid long lines.
2. **Classic Viewpoint**: Spend some time at a classic viewpoint, like the Eiffel Tower or Montmartre, where you can enjoy stunning views of the city.
3. **Wandering**: Allow time to wander through neighborhoods like Le Marais or Montmartre, enjoying food stops and scenic walks. This aligns with your preference for a relaxed experience rather than a packed schedule.
4. **Seine River**: Consider a stroll along the Seine River, which offers beautiful views and a chance to soak in the atmosphere of Paris.
5. **Sainte-Chapelle**: If time permits, visit Sainte-Chapelle for its stunning stained glass windows.
Remember to group nearby sights to minimize travel time across the city. Enjoy your weekend!
Now change the question:
exportMEMORY_QUESTION="How can I avoid overpacking my Paris weekend?"
mvn -q compile exec:java
The retrieved memories should shift toward the travel preference and logistics records. That is the point: we are not doing exact keyword lookup. We are asking Oracle to retrieve nearby memory records by semantic similarity, inside the configured metadata scope.
Prove the memory is durable
Stop the Java process. Run it again.
The memories are still there because they live in Oracle, not in the Java heap.
For this tutorial, the app re-seeds the five demo records on each run after deleting the current tenant/user seed records. If you want to watch persistence without reseeding, comment out the two lines that remove and seed the scoped demo memories, run once to insert, then run again with a different question.
For container-level persistence, the Docker Compose file uses a named volume:
volumes:
oracle-free-data:/opt/oracle/oradata
That means the database files survive docker compose down. If you run docker compose down -v, you remove the volume too.
Some topics for further reflection
The demo is intentionally small, but the design choices point in the right direction.
Use least privilege. Create a dedicated runtime schema or user. Do not run the app as SYS, SYSTEM, or a broad DBA account. Grant only the privileges needed to own or access the memory objects.
Scope every retrieval. Tenant and user filters should be mandatory for personal memory. Session filters can be optional for current-session memory. Shared project memory should have a different scope or memory type.
Treat memory as untrusted context. Retrieved text can be stale, user-authored, or malicious. It belongs below the system and developer instructions, and it should not be allowed to issue commands to the model.
Plan retention. Store timestamps and expiration fields. Delete expired rows by tenant, user, and memory type. Count before delete. Avoid unscoped deletes and casual truncates in shared tables.
Track embedding model changes. Store the embedding model name and dimensions in metadata. If you change models and dimensions, re-embed through a migration path rather than mixing incompatible vectors in an indexed column.
Index when the data justifies it. Exact search is fine for a tutorial table. Larger tables need vector indexes, metadata indexes, and measurement. Test HNSW and IVF with your workload instead of copying an index setting from another application.
Add -v only if you also want to remove the local database volume:
docker compose down -v
Where to go next
Paris, of course! My personal favorites are walking through the small streets in Montmartre and Le Marais, crêpe for petit dejeuner around the Jardin du Luxembourg and visiting some of the smaller museums like the Picasso, Maison de Victor Hugo or Musée Carnavalet. If you can venture out of town, avoid the crowds at Versialles with a visit to Fontainebleu, or drive through the vines in Champagne and take the cellar tour at Moët & Chandon.
But back to the topic of this article… The interesting next step is not making the prompt bigger. It is making memory more intentional.
Add a memory write path that stores only useful facts. Add consent and retention rules. Add tenant and user tests. Add an index once the table is large enough to need it. Add observability so you can see which memories were retrieved and why.
That is the practical shape of durable agent memory in Java: LangChain4j gives us the application-level model and embedding abstractions, OpenAI gives us the default chat and embedding models for this demo, and Oracle AI Database gives us a durable place to store memory text, metadata, and vectors together.
The nice part is that the first version fits in one small Maven app. That is exactly where I like a tutorial to start.
]]>https://redstack.dev/2026/05/27/give-a-java-agent-durable-memory-with-langchain4j-and-oracle-ai-database/feed/14549Add Event-Driven Workflows to Your Spring AI App with Oracle (Part 4 of 4)
https://redstack.dev/2026/05/27/add-event-driven-workflows-to-your-spring-ai-app-with-oracle-part-4-of-4/
https://redstack.dev/2026/05/27/add-event-driven-workflows-to-your-spring-ai-app-with-oracle-part-4-of-4/#respondWed, 27 May 2026 12:51:27 +0000https://redstack.dev/?p=4531Continue reading →]]>By the end of Episode 3 (video), the assistant could act. Tool calls let it look up orders, initiate returns, and create support tickets — real backend operations against Oracle, not simulated responses. But every one of those operations happened synchronously inside a single HTTP request. The chat endpoint called a tool method, that method did the work inline, and the response went back to the caller. All of it blocking, all of it inside the same transaction.
That works for simple demos. It starts breaking when the work is slow, depends on external systems, has multiple steps, or needs to be retried independently of the chat request.
The single most important idea in this episode is direct: the assistant starts workflows. The backend owns workflows.
In Episode 3, the tool was doing everything: validating the request, writing to Oracle, returning a result. If validation failed, the model got a clear error to relay. If it succeeded, the row was written and the request was done. Clean and correct for the demo.
But it ties the chat request tightly to the outcome of the workflow. If the workflow takes five seconds, the user waits five seconds for a reply. If the workflow involves multiple downstream steps, all of them need to complete inside the HTTP timeout. If something fails midway, the tool fails, and the model tries to explain an error that probably makes no sense to a customer.
The event-driven model separates those concerns. The tool’s job is to validate that the request makes sense and publish an event. The consumer’s job is to pick up that event and do the actual work. The user gets a fast response either way.
Figure 1 — The key architectural shift. On the left, the Episode 3 synchronous path: the tool call, validation, Oracle write, and response all happen in the same HTTP thread. On the right, the Episode 4 path: the tool call publishes an event and the response returns immediately at the response boundary. A downstream consumer handles validation and the database write in a separate transaction.
What changes
The architecture from Episodes 1 through 3 carries forward unchanged. The memory advisor, the vector-store advisor, and the Oracle-backed persistence are all still there. The chat client configuration is the same. AgentTools still exposes the same three @Tool methods with the same descriptions.
What changes is what those methods do internally, and what powers the new workflow layer: Oracle TxEventQ.
Oracle TxEventQ supports the Kafka wire protocol, but here it is accessed through JMS via the Oracle AQ JMS starter. From the Spring application’s perspective, the queue looks like any other JMS destination — JmsTemplate for publishing, @JmsListener for consuming. Nothing Kafka-specific in the application code.
The reason this matters: by Episode 4, Oracle is handling relational state, vector retrieval, conversation memory, and event streaming. No additional infrastructure.
Two event types. The constants on the record itself keep string literals out of the rest of the code. @JsonInclude(JsonInclude.Include.NON_NULL) means unused fields are omitted from serialized JSON — a return event does not include issue or priority, a support ticket event does not include reason.
The conversationId field carries the conversation ID from the original chat request through to the consumer. The consumer knows which conversation triggered the workflow. That is useful if the system eventually needs to send a message back into the conversation when work completes.
How the tool changes
The most visible change is in AgentTools. The initiateReturn method went from doing validation and database writes inline to doing a quick existence check and publishing an event:
@Tool(description="Initiate a return for an eligible delivered ShopAssist order after backend validation.")
@Transactional(readOnly=true)
publicStringinitiateReturn(
@ToolParam(description="The ShopAssist order ID, for example ORD-1001.")StringorderId,
@ToolParam(description="The customer's reason for the return.")Stringreason,
return"Order %s was not found, so a return workflow could not be started.".formatted(normalizedOrderId);
}
workflowEventPublisher.publish(newWorkflowEvent(
WorkflowEvent.RETURN_REQUESTED,
UUID.randomUUID(),
Instant.now(clock),
conversationId(toolContext),
normalizedOrderId,
reason.trim(),
null,
null
));
return"Return workflow started for order %s.".formatted(normalizedOrderId);
}
The method is now @Transactional(readOnly = true). It only writes one thing: nothing. It confirms the order exists, publishes a RETURN_REQUESTED event, and returns. The return string is “Return workflow started” rather than “Return initiated” — a deliberate phrasing change that the system prompt picks up on.
The third parameter, ToolContext toolContext, is new. Spring AI passes tool context to any tool method that declares it. AssistantService populates it with the conversation ID at call time:
The interface abstraction means unit tests can inject an in-memory publisher without touching JMS at all. The real implementation serializes the event to JSON, sends it as a JMS text message, and logs the key identifiers.
"Discarding unknown workflow event type eventType={} eventId={}",
event.eventType(),
event.eventId()
);
}
}
@JmsListener and @Transactional together mean the message dequeue and the database write are part of the same transaction. If the database write fails, the message stays on the queue.
The business validation that lived inside AgentTools in Episode 3 has moved to the consumer. handleReturnRequested re-checks order status, the return window, and whether a return is already in progress before calling save():
logger.info("Return workflow updated order state orderId={} status={}",orderId,order.getStatus());
}
The consumer does not trust the event blindly. It re-validates because events can be replayed or arrive out of order. The idempotency check — if the status is already PREPARING_RETURN, log and return without error — means processing the same event twice has no effect.
Figure 2 — The full event-driven flow. A chat request arrives, AgentTools confirms the order exists, JmsWorkflowEventPublisher serializes and sends the event to SHOPASSIST_WORKFLOW_TEQ, and the response returns at that point. Separately, WorkflowEventConsumer picks up the event via @JmsListener, re-validates the business rules, and writes to Oracle. The consumer’s @Transactional covers the dequeue and the database write as one unit.
The queue setup
Oracle TxEventQ is created by a SQL script that runs on every container start:
The EXCEPTION block catches the Oracle error codes for “queue already exists” and “queue table already exists” and silently continues. This makes the script safe to run against an existing volume — the first run creates the queue, every subsequent run does nothing.
The same script grants enqueue and dequeue privileges to the application schema, so the Spring application uses the same database credentials for JMS messaging that it uses for JDBC everywhere else.
The system prompt
The system prompt was updated to reflect the workflow semantics:
app:
assistant:
system-prompt:>
You are ShopAssist, a concise and practical support assistant for a demo
electronics store. Use retrieved policy context when it is available.
Use prior messages only when they are available through the active
conversation ID. Do not invent policy details. Do not invent order
details. Use tools for order status lookup, return initiation, and
support ticket creation. Treat tool results as the source of truth for
business actions and explain validation failures clearly. When a tool
returns a workflow-started message, relay it directly to the user. Do
not imply the action has already completed. Do not invent a workflow
status. If the answer is not grounded in retrieved context, current
conversation history, or tool results, say you do not know. Do not share
memory across conversation IDs.
The critical addition: “When a tool returns a workflow-started message, relay it directly to the user. Do not imply the action has already completed.”
Without that instruction, a model will naturally rephrase “Return workflow started for order ORD-1001” into something like “I’ve initiated your return” — which implies instant completion. That would be inaccurate and would confuse users who check their order status immediately afterward. The prompt constraint prevents it. This is a good example of the system prompt doing coordination work that code cannot easily do.
Startup behaviour
On startup, DataSeeder drains any stale messages from the queue before seeding the demo orders:
logger.info("Drained stale workflow event from {} on startup",queueName);
}
}
Events published in a previous run persist in TxEventQ across container restarts because the queue is backed by Oracle’s durable storage. Draining on startup ensures that old events from a previous demo session do not get processed unexpectedly when the application restarts with freshly seeded data.
Trying it
The same four demo orders from previous episodes are seeded: ORD-1001 (delivered, within the 30-day return window), ORD-1002 (shipped), ORD-1003 (delivered, outside the return window), ORD-1004 (processing).
Return workflow:
curl-s-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"Initiate a return for ORD-1001 because the product was defective."}' | jq
The tool confirms the order exists, publishes a RETURN_REQUESTED event, and returns immediately. In the application logs you will see two lines in quick succession: the publisher logging Published workflow event and the consumer logging Received workflow event, followed by Return workflow updated order state. The response was already back at the client before the consumer finished.
Support ticket workflow:
curl-s-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"Create a high-priority support ticket for ORD-1002 because shipping is stuck."}' | jq
The tool verifies the order exists, publishes a SUPPORT_TICKET_REQUESTED event, and returns. The consumer inserts the ticket row with priority HIGH.
After both requests, the database reflects the results:
SELECT ORDER_ID, STATUS FROM CUSTOMER_ORDER;
ORD-1001 shows PREPARING_RETURN. The other three orders are unchanged.
SELECT TICKET_ID, ORDER_ID, PRIORITY, STATUS FROM SUPPORT_TICKET;
One ticket row for ORD-1002 with priority HIGH and status OPEN.
The important thing to notice: the assistant reported “Return workflow started for ORD-1001” rather than “Return initiated”. The system prompt worked. The model did not imply the return was already complete.
Where things stand
Episode 1 made the assistant knowledgeable. Episode 2 made it remember. Episode 3 made it act. Episode 4 connects those actions to backend workflows.
Figure 3 — Oracle’s role across all four episodes. The relational tables and vector store arrived in Episode 1. Chat memory was added in Episode 2. The support ticket table came in Episode 3. Oracle TxEventQ event streaming arrived in Episode 4. Single database connection pool, no additional infrastructure.
At this point Oracle is the backing store for every layer of the application: relational order data in CUSTOMER_ORDER, vectorized policy documents in the Oracle Vector Store table, conversation history in SPRING_AI_CHAT_MEMORY, support ticket records in SUPPORT_TICKET, and event streaming through SHOPASSIST_WORKFLOW_TEQ. All of it through one database, one connection pool.
The assistant’s role throughout the series has stayed consistent. It retrieves knowledge. It remembers conversations. It initiates actions. It starts workflows. In every case, the backend owns what happens next. That boundary — the model orchestrates, the backend decides and executes — is what makes the system trustworthy rather than unpredictable.
]]>https://redstack.dev/2026/05/27/add-event-driven-workflows-to-your-spring-ai-app-with-oracle-part-4-of-4/feed/04531Productionizing Oracle Database Metrics Exporter: Least Privilege, Private Scraping, and Operational Ownership
https://redstack.dev/2026/05/26/productionizing-oracle-database-metrics-exporter-least-privilege-private-scraping-and-operational-ownership/
https://redstack.dev/2026/05/26/productionizing-oracle-database-metrics-exporter-least-privilege-private-scraping-and-operational-ownership/#respondTue, 26 May 2026 13:30:00 +0000https://redstack.dev/?p=4519Continue reading →]]>The local demo worked.
/metrics responds. Prometheus scrapes the target. Grafana shows panels. Maybe oracledb_up is 1 in your deployed version, and database-side signals finally sit near application latency, deployment events, queue behavior, and other service telemetry.
That is a useful milestone.
It is not production readiness.
Productionizing Oracle Database Metrics Exporter means controlling what the exporter can read, who can scrape it, what labels leave the database boundary, and who owns alerts, dashboards, runbooks, upgrades, and readiness review.
A working local scrape proves that Oracle Database Metrics Exporter can connect to a database and expose metrics in a Prometheus-compatible format. Production asks a different set of questions. What database identity does the exporter use? Which database views and tables can that identity read? Where are credentials, connect strings, and wallets stored? Who can scrape /metrics? Which labels leave the database boundary? Are custom SQL metrics safe at production scale? Which alerts page humans? Who owns the exporter when it breaks?
The production model is simple to state and easy to underestimate:
Treat Oracle Database Metrics Exporter as both a privileged Oracle Database client and a private scrape target.
That is the thesis of this article. Productionizing Oracle Database Metrics Exporter is not mainly about getting another container to run. It is about controlling what the exporter can read, who can scrape it, what labels leave the database boundary, and who owns the alerts, dashboards, runbooks, upgrades, and rollback path.
For developers building AI and database-backed applications, this matters because Oracle Database may sit directly in the request path. A RAG service might use vector search, JSON metadata filters, relational joins, queue tables, conversation memory, and audit writes. An agentic workflow system may persist state, tool calls, retries, and human approval steps. An ingestion service may compete with retrieval traffic.
When those systems slow down, database observability becomes part of user experience.
The production controls, however, are not AI-specific. They are the same controls you would want for any database-backed service: least privilege, protected credentials, private scraping, reviewed labels, safe custom SQL, actionable alerts, and owned runbooks.
Oracle Database Metrics Exporter is not trying to be Oracle Enterprise Manager, OCI Database Management, or a commercial APM/database-monitoring suite. Those platforms can provide broader discovery, incident management, tuning workflows, dashboards, and operational governance, depending on deployment, licensing, configuration, and operating model. The exporter’s value is narrower: it brings Oracle Database metrics into Prometheus-compatible pipelines that many developer platforms already operate.
That narrower scope is useful. It also means production readiness is your responsibility.
A few terms before the production review
Before we move into the review path, it helps to fix the vocabulary. The terms are common, but small differences matter in production conversations.
An exporter is a process that collects or queries data from another system and exposes it in a metrics format. In this case, Oracle Database Metrics Exporter connects to Oracle Database and exposes metrics for a scraper.
A scraper is a monitoring component, usually Prometheus or an OpenTelemetry Collector Prometheus receiver, that periodically reads the exporter’s metrics endpoint.
Least privilege means granting only the database and platform access needed for approved metrics, not broad access because it is convenient.
A custom SQL metric is a metric defined by an operator or application team using a SQL query, rather than a default metric shipped with the exporter.
Label cardinality is the number of distinct label values, or label combinations, that a metric can produce.
A runbook is a short operational document that tells responders what an alert means, what to check first, how to reduce impact, and when to escalate.
A production-readiness review is a pre-rollout review that checks identity, grants, secrets, network exposure, metrics, labels, alerts, dashboards, runbooks, ownership, upgrades, and rollback criteria.
Those definitions matter because they keep the review grounded. This is not only a deployment review. It is a trust-boundary review.
Version and naming notes
Verify names, image paths, and tags against the current Oracle documentation before rollout.
At the time of writing (May 2026) the current version of Oracle Database Metrics Exporter is 2.3.1, and Oracle’s installation docs used an image path in the form container-registry.oracle.com/database/observability-exporter:2.3.1.
Treat that as a review point, not as a promise that your environment should use the same version.
Before rollout, verify the current release, image tag, command-line flags, default metrics, and configuration syntax against Oracle’s repository and documentation. Also inspect the runtime --help, the default metrics file for the exact tag, and live /metrics output from the image you deploy.
Understand how production changes the boundary
In local development, the topology is usually compact. One person can understand the whole path.
Developer laptop
├─ Oracle Database or test database
├─ Oracle Database Metrics Exporter
├─ Prometheus
└─ Grafana
That setup is valuable because it proves the mechanics. The exporter can connect to Oracle Database. Prometheus can scrape it. Grafana can query Prometheus. The developer can troubleshoot each hop.
Production changes the boundary.
In local development, /metrics is a convenience. In production, /metrics is an internal data boundary.
In local development, broad test access may be acceptable for a disposable lab. In production, exporter grants must be reviewed metric by metric.
In local development, labels are exploratory. In production, labels affect cost, privacy, retention, remote write, dashboard access, and alert annotations.
In local development, the developer owns everything. In production, ownership must be explicit.
The readiness path is less about one deployment shape and more about a sequence of decisions.
This is a readiness flow, not a universal deployment architecture. It shows the decisions that turn “the demo works” into “this exporter is an operated production component.”
Bring the right context to the review
A production review cannot approve an exporter in the abstract. Reviewers need to know exactly what will run, what it will read, what it will expose, and who will operate it.
Bring the exporter version, image tag, runtime --help output, enabled default metrics, custom SQL metrics, and sample /metrics output from the deployed version. Bring the database topology, required grants, credential path, wallet or TCPS requirements, exporter-to-database network path, and scraper-to-exporter network path. Bring the Prometheus or OpenTelemetry Collector configuration, retention and remote-write destinations, dashboard audience, alert routing, upgrade plan, and rollback plan.
Database topology matters. A deployment may be single-instance, CDB/PDB, RAC, Autonomous Database, managed service, on-premises, cloud-hosted, or a combination. One grant recipe and one network policy rarely cover all of those cases.
The review should include application developers, DBAs, SREs or platform engineers, security reviewers, observability owners, and the product or application owner if alerts imply user impact.
This may sound heavy for a “small exporter.” It is not heavy for a component that connects to Oracle Database, queries database views, exposes database-derived metrics, and feeds alerting systems.
Start with the database identity
The first production decision is the database identity.
The exporter should use a dedicated monitoring identity where possible, not an application schema, personal account, DBA account, or shared administrative user.
That identity matters because the exporter is a database client. Every metric maps to some database query. The grants behind those queries define what database information can leave the database boundary. A dedicated identity simplifies access review, audit, rotation, revocation, and incident response.
Oracle’s exporter docs recommend connecting with the lowest possible privileges and roles necessary for the exporter to run. Oracle Database privilege and role behavior is covered in the Oracle Database Security Guide, and many default metrics query dynamic performance views documented in the Oracle Database Reference.
This is not unique to Oracle Database Metrics Exporter. Datadog, Dynatrace, New Relic, custom SQL jobs, and other Oracle Database monitoring paths also need a database identity, grants, credentials, and network reachability.
The safe question is not “Which tool avoids privileges?” The safe question is “Which metrics are approved, which objects do they require, and who reviews the grants?”
-- Illustrative only: grant only views required by approved metrics.
GRANTSELECTON SYS.GV_$INSTANCE TO exporter_monitor;
GRANTSELECTON SYS.GV_$SESSIONTO exporter_monitor;
This snippet is not a complete grant recipe. It shows the shape of a reviewed monitoring identity. The object list must come from the exact default metrics and custom metrics you approve for your topology.
Test grants using the same connection method and session role behavior the exporter uses. Do not assume a query succeeds for the monitoring user in SQL Developer, SQLcl, or an administrative session in exactly the same way it will succeed inside the exporter.
Oracle’s docs may list broad roles such as SELECT_CATALOG_ROLE as a way to make built-in metrics work. A broad role may be documented as a convenience path, but it is not automatically least privilege. Least privilege means reviewing the enabled metrics and granting only the required access where practical for your environment. If your organization allows SELECT_CATALOG_ROLE for operational reasons, document that as an explicit risk acceptance rather than describing it as least privilege.
Do not assume one grant recipe works for single-instance databases, CDB/PDB deployments, RAC, Autonomous Database, managed database services, and cloud-hosted databases. The topology matters.
Manage credentials and wallets as production secrets
After identity comes credential handling.
Treat exporter credentials with the same seriousness as application database credentials. The secret set may include the username, password, password files if supported by the deployed exporter version, Oracle Wallet or TCPS material where required, connect strings, service names, database endpoints, vault references, and tokens used by the deployment platform.
Kubernetes Secrets are a delivery mechanism, not a complete secret-management solution. They can be part of an approved path, but they do not answer rotation, access review, encryption, redaction, backup, or incident response by themselves. See the Kubernetes Secrets documentation for the platform behavior, then apply your organization’s secret-management policy.
Oracle’s 2.3.1 docs show environment-variable connection settings and a configuration-file model that includes fields such as passwordFile and tnsAdmin. Verify the exact field names, nesting, and supported credential methods for the image tag you deploy.
A conceptual configuration shape might look like this:
# Conceptual pattern only. Verify exact field names, nesting,
# and supported credential methods against the current Oracle docs
The important point is not this exact YAML. The important point is the production habit: do not hard-code passwords in manifests or examples. Do not include real service names, tenant names, wallet paths, or connect descriptors in shared docs. Choose one supported credential path, document it, rotate it, and test exporter behavior during rotation.
If the database requires wallets or TCPS, review filesystem permissions, mount paths, renewal process, wallet distribution, wallet revocation, logging behavior, backup exposure, and incident response process.
If you use a vault integration, verify the exact syntax and support level for the deployed exporter version. Do not assume support for OCI Vault, Azure Key Vault, HashiCorp Vault, Secure External Password Store, or external authentication unless the current docs and your runtime test confirm it.
Also check logs. Exporter logs can be useful during connection failures, but logs may include service names, wallet paths, privilege errors, SQL errors, or other sensitive context. Redaction belongs in the production design, not only in the incident review.
Before sharing logs, screenshots, dashboard JSON, alert examples, or runbook excerpts outside the approved audience, review them for database names, service names, schema names, SQL text, tenant identifiers, wallet paths, hostnames, and internal network details.
Keep /metrics private
Once the exporter can connect to the database, protect the scrape endpoint.
The exporter endpoint should not be exposed as a public internet endpoint.
/metrics contains database-derived operational data. Labels may reveal system names, SQL identifiers, SQL text, schema names, service names, queue names, usernames, tenant identifiers, prompts, documents, workflow names, or application-specific values. Even if your initial metric set looks harmless, future default metrics, custom SQL metrics, or exporter upgrades can change what appears at the endpoint.
Prometheus’ model makes the endpoint powerful because scrapers can pull metrics directly. That same model makes endpoint exposure important. Prometheus documents the scrape configuration model in its configuration reference and explains metric labels in the data model.
The practical takeaway is simple: if a client can scrape the exporter, it can see what the exporter exposes before downstream relabeling, dropping, retention, or remote-write filtering.
A private Kubernetes ClusterIP Service is not, by itself, an access-control model. NetworkPolicy can help restrict access, but Kubernetes NetworkPolicy enforcement depends on the cluster networking implementation. Creating a NetworkPolicy in a cluster whose CNI does not enforce NetworkPolicy does not protect the endpoint. Also remember that NetworkPolicy is additive: pods are not isolated for ingress or egress until a policy selects them for that direction. Test enforcement from the Prometheus pod, from an unapproved pod in the same namespace, and from an unapproved pod in another namespace.
TLS and authentication through --web.config.file are version-sensitive and should be verified against the exporter’s current support for Prometheus exporter-toolkit-style web configuration. Do not assume TLS or authentication is enabled by default. Also treat TLS and authentication as policy decisions, not only feature checks: confirm whether your organization requires encrypted scrape traffic, authenticated scrapers, certificate rotation, service-mesh policy, or additional authorization controls for database-derived metrics.
Here is an ingress NetworkPolicy pattern that allows only an approved Prometheus pod to reach the exporter:
# Pattern only. Verify namespace labels, pod labels, port names,
# and CNI NetworkPolicy enforcement in your cluster.
# This is an L3/L4 control, not a replacement for TLS, authentication,
# service mesh policy, RBAC, or data-governance review.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-prometheus-to-oracle-exporter
namespace: app-observability
spec:
podSelector:
matchLabels:
app: oracle-db-metrics-exporter
policyTypes:
- Ingress
ingress:
-from:
-namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
podSelector:
matchLabels:
app.kubernetes.io/name: prometheus
ports:
-protocol: TCP
port: 9161
That pattern is useful only if the labels, namespaces, ports, and CNI enforcement match your cluster. It does not replace TLS, authentication, RBAC, service mesh policy, or data-governance review.
NetworkPolicy limits which pods can open a connection; it does not prove the client is an approved scraper identity at the application layer and does not encrypt the scrape payload.
Production review also includes the exporter’s outbound path to Oracle Database:
# cloud gateways, service mesh, DNS behavior, and CNI behavior may require
# a different model. DNS can require TCP/53 as well as UDP/53.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: restrict-oracle-exporter-egress
namespace: app-observability
spec:
podSelector:
matchLabels:
app: oracle-db-metrics-exporter
policyTypes:
- Egress
egress:
-to:
-ipBlock:
cidr: 10.20.30.40/32
ports:
-protocol: TCP
port: 1521
-to:
-namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
-protocol: UDP
port: 53
-protocol: TCP
port: 53
RAC, SCAN listeners, Autonomous Database, private endpoints, cloud gateways, DNS behavior, service mesh sidecars, and CNI-specific FQDN policy can require different designs. An egress policy that is too narrow can break database failover, wallet retrieval, or DNS. An egress policy that is too broad may fail the review.
For RAC, SCAN listeners, private endpoints, and managed database services, prefer a topology-specific tested egress design over a single hard-coded database IP if failover or endpoint rotation is part of the service behavior.
The right answer is topology-specific and tested.
Scrape deliberately with Prometheus or the OpenTelemetry Collector
After the endpoint is private, make the scrape path explicit.
Oracle Database Metrics Exporter exposes Prometheus-compatible metrics. Prometheus scrapes /metrics, stores time series, evaluates PromQL, and can run alert rules. The OpenTelemetry Collector can scrape Prometheus-format metrics through the Prometheus receiver and forward metrics through a Collector pipeline. Grafana visualizes metrics by querying Prometheus or another metrics backend.
Do not blur those roles. Grafana does not make the exporter safe. It makes reviewed metrics visible. The OpenTelemetry Collector can be part of the scrape-and-forward path, but do not claim the exporter natively pushes OTLP unless you verify that behavior for the exact exporter version.
A Prometheus scrape pattern should make interval and timeout deliberate:
# Pattern only. Verify service discovery, TLS, authentication,
# relabeling, job labels, timeout, and interval for your environment.
Prometheus scrape syntax is documented in the Prometheus configuration reference. Static targets keep the example short; production may use Kubernetes service discovery, file service discovery, relabeling, TLS, authentication, or a service mesh.
If your platform standardizes on OpenTelemetry Collector, the Collector can own the scrape:
# Pattern only. Verify that your Collector distribution includes
# the Prometheus receiver and that your backend accepts the resulting metrics.
# Set according to your gateway's actual TLS configuration.
insecure: false
service:
pipelines:
metrics:
receivers:[prometheus]
processors:[batch]
exporters:[otlp]
The OpenTelemetry Collector configuration model is documented in the Collector docs, and the Prometheus receiver lives in the OpenTelemetry Collector Contrib project. Verify receiver availability in the Collector distribution you deploy.
Review scrape interval, scrape timeout, exporter query timeout if supported, and custom metric timeout together.
A short scrape interval can increase database query frequency. A long scrape interval can delay detection and reduce dashboard resolution. Multiple Prometheus servers or Collectors scraping the same exporter can multiply database work if the exporter collects on scrape rather than serving cached results. Verify the exporter’s collection behavior for your deployed version before adding HA scrapers, federation, or parallel Collector pipelines.
Decide which system owns scrape-health alerting before production rollout.
Review default metrics before enabling them broadly
Default metrics are useful because they give teams a starting point. They are still database queries and labels.
Before enabling them broadly, inspect the exact default metrics for the exporter tag you deploy. Use Oracle docs, release notes, and the repository as source anchors, but do not assume the repository main branch matches your deployed image. Compare the tagged default metrics file, the image contents if available, and live /metrics output from your environment.
For each enabled metric, record the metric name, metric type, database views or SQL behind it, required grants, exposed labels, expected cardinality, dashboard or alert usage, interpretation owner, and approval decision. Also record whether any label can contain sensitive identifiers. That review note does not need to be complex, but it should be explicit enough that a DBA, application owner, SRE, and security reviewer can understand what the exporter is allowed to expose.
For the live /metrics review, capture a sample from the same network path the scraper will use. Confirm the exporter build/version if exposed, the oracledb_up value if that metric is present, expected default metrics, expected custom metrics, unexpected labels, high-cardinality labels, sensitive label values, scrape duration or error self-metrics if present, and whether metric names match dashboard and alert queries.
Inspect oracledb_up, if present in your deployed version, because it tells you whether the database is reachable from the exporter’s point of view. Confirm the metric name in live /metrics before wiring dashboards or alerts.
Also inspect exporter self-metrics if they are present in your deployed version. Examples to look for may include scrape error, scrape duration, and scrape count metrics, but names and semantics must be confirmed from live /metrics for the exact image you deploy.
Those metrics help you distinguish database signals from exporter collection problems.
Then inspect session metrics, activity metrics, wait metrics, tablespace or resource metrics, and top SQL metrics if present in your deployed version. Labels such as sql_id and sql_text need special review. SQL IDs, SQL text, usernames, schemas, module names, service names, tenant identifiers, queue names, and workflow names may be sensitive depending on your environment.
Top SQL metrics are triage hints, not a tuning workflow. They can point responders toward the next question, but they do not replace AWR, ASH, SQL Monitor, execution-plan analysis, SQL Tuning Advisor, ADDM, Performance Hub, or DBA workflows.
Truncated SQL text is not automatically safe. A default metric is not automatically approved for every environment.
Metrics guide investigation. They do not prove root cause by themselves.
Add custom SQL only after review
Custom SQL metrics are powerful because they expose business-relevant database signals. They are risky because they can add query cost, sensitive labels, fragile SQL, new grants, and high-cardinality dimensions.
Good custom metric candidates answer bounded operational questions. A queue-depth metric by a small approved queue-name list can be useful. So can failed job counts by a bounded status list, stale workflow counts aggregated by workflow type, ingestion backlog by approved pipeline name, or RAG document indexing backlog aggregated by approved status categories.
Poor candidates are metrics that turn user, request, document, prompt, session, tenant, URL, file, exception, raw SQL text, or workflow-instance values into labels. Queries that scan large application tables every scrape are also poor candidates, even if they look harmless in development.
A bounded queue-depth metric might have this shape:
# Pattern only. Verify current custom metric format, field names,
# column-name matching behavior, timeout behavior, and metric-name
# generation against the exporter docs and the exact image tag you deploy.
#
# Oracle SQL returns unquoted identifiers in uppercase metadata. Depending
# on exporter behavior, you may need quoted aliases such as "queue_name"
# and "depth", or you may need to use the uppercase names expected by the
# exporter version you run.
[[metric]]
context = "app_queue"
request = """
SELECT
queue_name AS "queue_name",
COUNT(*) AS "depth"
FROM app_work_queue
WHERE status = 'READY'
GROUP BY queue_name
"""
labels = ["queue_name"]
[metric.metricsdesc]
depth = "Number of ready items in an approved application queue"
This example is intentionally small. It assumes queue_name is a short approved list, not a tenant ID, workflow ID, or arbitrary customer-provided value. It also assumes the query cost has been reviewed at production scale.
Before using a custom metric in production, test the exact query and exporter configuration together and confirm that the returned column names match the labels and metric descriptors expected by the exporter.
For application tables, review the execution plan, indexes, expected row counts, and concurrency impact at the chosen scrape interval. A custom metric that performs a full table scan every 30 seconds is production workload, not passive observation.
For each custom SQL metric, ask what operational question it answers, who will use it, which dashboard or alert consumes it, which grants it requires, how expensive it is at production scale, which scrape interval and timeout apply, what happens if it fails, whether labels are bounded, whether labels are safe to expose, and who owns the query when schema changes.
Custom SQL metrics are production code. They need owners, tests, review, disablement paths, and retirement criteria.
Control label cardinality before it controls your backend
Label cardinality is the number of distinct label values, or combinations of label values, a metric can produce. In Prometheus-style metrics, every unique combination of metric name and label values becomes a distinct time series.
That is useful when labels are bounded and meaningful. It becomes expensive and noisy when labels contain unbounded values such as user IDs, request IDs, document IDs, prompt IDs, session IDs, SQL text, or workflow instance IDs.
The Prometheus data model identifies each time series by metric name and label set. Changing label values, adding labels, or removing labels changes the resulting time series. The Prometheus configuration docs also warn that label dropping must preserve meaningful and unique series.
Dropping labels is not always safe; it can merge series and change the meaning of a metric.
Prefer bounded labels such as status, region, approved service name, queue name from a small approved list, wait class, or a small reviewed workflow type list.
Avoid unbounded labels such as user ID, request ID, document ID, session ID, prompt ID, URL, SQL text, workflow instance ID, exception text, or anything derived from arbitrary user or workload input.
Treat SQL text as sensitive by default. Treat sql_id as review-worthy because it can produce many series and may be correlated with query text elsewhere. Treat schema names, usernames, service names, tenant identifiers, prompt IDs, document IDs, queue names, and workflow IDs as exported data, not harmless metadata.
You can inspect exporter series and high-risk labels with scoped PromQL patterns:
count by (__name__) ({job="oracle-db-metrics-exporter"})
count by (__name__, sql_id) ({job="oracle-db-metrics-exporter", sql_id!=""})
count by (__name__, sql_text) ({job="oracle-db-metrics-exporter", sql_text!=""})
Use broad PromQL selectors carefully in large production backends. Scope by job, namespace, environment, database service, or another approved label so the inspection query itself does not become a problem.
Do not rely only on backend filtering. Prometheus relabeling, remote-write filtering, Collector processors, and backend retention policies can reduce downstream storage or visibility, but they do not protect the exporter endpoint itself.
If a label appears at /metrics, any approved scraper or accidental endpoint exposure can see it before downstream filtering.
Cardinality review belongs before rollout, not after storage costs rise, dashboard queries slow down, or alert labels leak sensitive identifiers.
Alert on failures that need action
Alerts should start with failures that require action, not with every interesting database signal.
Good first alert categories include Prometheus being unable to scrape the exporter, the exporter being reachable while oracledb_up reports database reachability failure if that metric is present, exporter scrape or collection errors if those self-metrics are present, scrape duration approaching the timeout budget if that self-metric is present, custom metric timeouts or failures if the exporter exposes that signal, missing required metrics, and cardinality spikes after a deployment or metric change.
Be cautious with raw database-performance alerts until you have baselines and ownership.
Prometheus alert rules are documented in the Prometheus alerting rules guide. The following example is a pattern, not a universal rule file.
Verify metric names, labels, thresholds, severity, and routing against your exporter version and alerting standards.
# Pattern only. Confirm these metric names and semantics in live /metrics
# for your exact exporter version before enabling these rules.
# The self-metric names shown here are examples to verify, not guarantees.
groups:
-name: oracle-db-metrics-exporter.rules
rules:
-alert: OracleDatabaseMetricsExporterTargetDown
expr: up{job="oracle-db-metrics-exporter"} == 0
for: 5m
labels:
severity: warning
annotations:
summary:"Oracle Database Metrics Exporter target is down"
description:"Prometheus cannot scrape the Oracle Database Metrics Exporter target."
summary:"Oracle Database Metrics Exporter scrape duration is high"
description:"Exporter collection duration is approaching the expected scrape budget."
The up alert is Prometheus-side target health. The oracledb_up alert, if that metric exists with the expected semantics in your deployed version, is database reachability from the exporter’s point of view, not proof of application health or full database health.
Also decide how to handle missing expected metrics. An expression such as oracledb_up == 0 does not alert if the oracledb_up series is absent. If the metric is required for your production design, add a separate absent-series check or dashboard validation, and test it during exporter upgrades, relabeling changes, and Collector pipeline changes.
The scrape-error and scrape-duration examples require exporter self-metrics that must be confirmed in your deployed version. Tune thresholds to your scrape_timeout, exporter query timeout if supported, database topology, and approved custom metrics.
Avoid paging on raw waits, sessions, or top SQL without baselines. Prefer warnings, tickets, or investigation dashboards until the team understands normal workload patterns. Do not include sensitive label values in alert annotations.
Route exporter health alerts to the monitoring-chain owner. Route database reachability alerts according to the platform or DBA incident model. Route custom metric alerts to the team that owns the metric’s business meaning.
If Enterprise Manager, OCI Database Management, Datadog, Dynatrace, New Relic, Grafana, Prometheus, and cloud alarms all watch the same database, alert ownership matters more than alert volume. Choose which system pages humans, which system opens tickets, and which systems provide context only.
A duplicate page is not resilience. It is operational noise.
Write runbooks before alerts page someone
Every paging alert should have a runbook before it pages a human.
A useful runbook does not need to be long. It needs to tell responders what the alert means, what user impact is known or unknown, what to check first, what common causes exist, what mitigations are safe, when to escalate, and how to roll back or disable a broken component.
A runbook for database reachability from the exporter might look like this:
Runbook pattern:
Alert:
OracleDatabaseMetricsExporterDatabaseUnreachable
Meaning:
The exporter is reachable, but its Oracle Database reachability check is failing.
Possible user impact:
Unknown from this alert alone. Check application health and database service status.
First checks:
- Is the exporter target still up?
- Did the database service, listener, wallet, DNS, route, or firewall change?
- Did the exporter credential expire, rotate, or lock?
- Is the database service reachable from the exporter network?
- Do exporter logs show account lock, password, role, privilege, wallet, or service-name errors?
- Did a CDB/PDB service name or Autonomous Database wallet change?
Escalate to:
DBA/platform owner for database service or credential issues.
SRE/observability owner for exporter, scrape, or network path issues.
Safe mitigations:
- Roll back the last exporter configuration change if it caused the failure.
- Restore the prior secret or wallet version if approved.
- Disable a broken custom metric if it is blocking collection and the runbook allows it.
Do not:
- Share unredacted logs.
- Add broad grants during incident response without approval.
- Assume this alert proves application outage or database root cause.
For OracleDatabaseMetricsExporterTargetDown, first check whether the exporter pod or process is running, whether the Service or target address is correct, whether labels or service discovery changed, whether NetworkPolicy blocks Prometheus, whether TLS or authentication is misconfigured, whether the scrape timeout changed, and whether Prometheus can reach the endpoint from its own network.
For a database reachability alert such as oracledb_up == 0, first confirm that the metric exists and has the expected semantics for your exporter version. Then check whether the exporter itself is reachable, whether the database service, listener, wallet, DNS, route, or firewall changed, whether the credential expired or locked, whether the service is reachable from the exporter network, and whether exporter logs show account, role, privilege, wallet, or service-name errors.
For missing expected metrics, check the exporter version, live /metrics output, relabeling rules, Collector pipeline, backend ingestion, metric name changes, and dashboard or alert query assumptions.
For exporter scrape errors, identify which metric or query failed. Check grants, topology-specific views, custom SQL changes after schema migration, query timeouts, wallet paths, credential paths, and log redaction before sharing details.
For slow scrape duration, check whether custom metrics changed, whether scrape interval or timeout changed, whether a query scans more data after workload growth, whether the database is under load, whether multiple scrapers are hitting the same exporter, and whether the exporter is collecting too much per scrape.
For a cardinality spike, identify which metric name grew and which label drove the growth. Check recent custom metric deployments, default metric changes, exporter upgrades, and whether a label started carrying tenant, user, request, SQL text, document, prompt, or workflow identifiers.
Escalation should match the failure mode. Exporter process or scrape path issues belong with SRE, platform, or observability owners. Database reachability and grants belong with DBA or platform owners. Custom SQL metric failures belong with the application owner plus DBA review. Sensitive labels involve security and observability owners. Dashboard or alert query breakage belongs with the observability owner.
Build dashboards for decisions, not decoration
A production dashboard should help responders decide what to do next. It should not be a wall of raw database counters.
Grafana dashboards are documented in the Grafana dashboards docs, and Grafana can query Prometheus through the Prometheus data source. But Grafana is the dashboard and, in some organizations, the alerting surface. It does not make the exporter safe; it makes reviewed metrics visible.
A practical production dashboard should start with monitoring-chain health: Prometheus target status for the exporter, exporter scrape errors if exposed, and exporter scrape duration if exposed. Then it should show database reachability through oracledb_up if present in your deployed version and recent reachability transitions.
After that, add collection reliability and cost: last scrape error if exposed, scrape totals if exposed, collection duration versus scrape timeout if exposed, and custom metric failures or timeouts if exposed.
Only then should the dashboard move into workload context: sessions and activity indicators, wait categories with bounded labels, and top SQL or hotspot signals only if labels and audience are approved.
Application/database signals can follow: reviewed queue depth, ingestion backlog, workflow state counts, or RAG indexing backlog by approved status. Finally, add change overlays for application deployments, database changes, schema migrations, exporter upgrades, credential rotations, and network-policy changes.
The best panels answer operational questions:
Is the monitoring path healthy?
Is the database reachable from the exporter?
Did collection cost change?
Which bounded workload category changed?
Where should we look next?
Which recent deployment, schema migration, credential rotation, or network-policy change lines up with the signal?
Do not expose SQL text panels broadly. Do not put sensitive labels in public team dashboards. Use scoped variables to avoid massive PromQL fan-out. Review dashboard variables as carefully as panels. A variable query that lists sql_text, usernames, tenant identifiers, service names, or workflow IDs can expose sensitive values even if no panel displays them directly.
Document the intended audience for each dashboard.
A dashboard for DBAs can reasonably expose different details than a broad application team dashboard.
Top SQL or hotspot panels should be restricted or omitted unless SQL labels have been reviewed and the audience is appropriate. Use top SQL signals as hints for the next question, not as proof of root cause.
Assign operating ownership
If everyone can use the exporter but nobody owns it, the exporter becomes another production dependency with no accountable operator.
Ownership must be explicit before rollout. A short owner map is usually more valuable than a long architecture document.
Before rollout, name the team or person responsible for exporter deployment, exporter database identity, grant approval, default metric approval, custom SQL metric approval, Kubernetes Service, NetworkPolicy, secret delivery, Prometheus or Collector scrape configuration, alert routing, dashboard access, response when up == 0, response when database reachability fails from the exporter, exporter upgrade review, and emergency disablement of a broken custom metric.
A workable responsibility split often looks like this:
Application developers propose application-specific custom metrics and explain their business meaning.
Observability teams review metric naming, labels, cardinality, dashboards, retention, and remote write.
Product or application owners define user impact and which alerts justify paging.
Shared responsibility is fine. Unowned responsibility is not. Ownership must include break/fix, upgrades, credential rotation, dashboards, alerts, and emergency disablement.
The emergency disablement point matters. A broken custom SQL metric can fail after a schema migration. A new label can create a cardinality spike. A credential rotation can break collection. Someone needs authority to disable, roll back, or restrict the exporter path safely while preserving the incident trail.
Review upgrades before changing the exporter
Treat an exporter upgrade like a monitoring schema change. It may not change application code, but it can change what your observability platform stores, alerts on, and exposes to users.
Before changing the exporter version, compare the old and new behavior:
Exporter upgrade review prompt:
Before changing the exporter version, compare:
- Release notes and changelog.
- Image tag.
- Runtime --help output.
- Default metric files.
- /metrics output before and after.
- Added, removed, or renamed metrics.
- Changed metric types.
- Added, removed, or changed labels.
- Cardinality impact.
- Grants required by default metrics.
- Custom metric behavior.
- Wallet, password file, vault, and external-auth configuration.
- --web.config.file behavior if TLS/auth is used.
- Prometheus scrape success.
- OpenTelemetry Collector scrape path, if used.
- Dashboard queries.
- Alert rules.
- Rollback steps.
- Approval owner.
Use the Oracle GitHub releases, repository, documentation, runtime --help, default metrics file, and live /metrics output for the exact image tag. Avoid unreviewed latest tags in production.
Metric names, labels, and types can change. New default metrics may require new grants. Removed or renamed metrics can break dashboards and alerts. Added labels can increase cardinality or expose sensitive data. Credential, wallet, password-file, vault, TLS, authentication, query timeout, and custom metric syntax can change.
Migration from an older or community exporter such as iamseth/oracledb_exporter is not “just swap the image.” Metric names, labels, grants, dashboards, alerts, and scrape behavior may differ.
Grafana Alloy’s prometheus.exporter.oracledb is an adjacent route for Grafana-centric teams, but it should be reviewed as its own exporter implementation and lifecycle. Do not assume it is identical to Oracle Database Metrics Exporter unless you verify the embedded implementation, metric set, labels, grants, wallet behavior, and upgrade path.
Use a production-readiness review before rollout
A deployment is ready for shared or production use only after the team can answer the production questions, not just after the endpoint returns metrics.
Use this review near the end of rollout planning:
Production-readiness review:
A deployment is ready for shared or production use only after the team can answer:
- Identity: Is the exporter using a dedicated monitoring identity?
- Grants: Are grants approved for the exact default and custom metrics enabled?
- Topology: Have CDB/PDB, RAC, Autonomous Database, managed database, or single-instance differences been reviewed?
- Secrets: Are passwords, wallets, connect strings, and tokens delivered through approved secret paths?
- Rotation: Has credential rotation been tested?
- Endpoint: Is /metrics private?
- Network: Can only approved scrapers reach the exporter?
- TLS/auth: If required, is exporter endpoint TLS or authentication configured and tested?
- Scrape config: Are interval, timeout, labels, and job names deliberate?
- Default metrics: Has the team reviewed default metric names, labels, query cost, and grants?
- Custom metrics: Is every custom SQL metric owned, reviewed, bounded, and useful?
- Labels: Are sensitive and high-cardinality labels removed, aggregated, or restricted before rollout?
- Prometheus/Collector: Is the scrape path clear and tested?
- Alerts: Do alerts represent actionable failures?
- Dashboards: Do dashboards support decisions and avoid exposing sensitive labels?
- Runbooks: Does every paging alert have a runbook?
- Retention: Are metrics retention and remote-write destinations approved?
- Access: Are dashboard and metrics-backend permissions appropriate?
- Ownership: Are deployment, grants, metrics, alerts, dashboards, and upgrades assigned to named teams?
- Upgrade plan: Is there a version review and rollback process?
- Rollback: Can a broken custom metric, scrape config, or exporter version be disabled quickly?
The expected result is a rollout decision:
Approved for production.
Approved with restrictions.
Deferred pending grants review.
Deferred pending label review.
Deferred pending network controls.
Deferred pending runbooks or ownership.
Rejected until the design changes.
A checklist does not replace technical review. It makes the review concrete. If the team cannot name the identity, grants, scrape path, labels, alerts, dashboards, runbooks, owners, upgrade process, and rollback plan, the rollout is not ready.
The practical takeaway
A production exporter rollout is ready when the team can name the database identity, list the approved grants, protect the credentials, explain who can scrape /metrics, defend every high-risk label, show actionable alerts and dashboards, link to runbooks, identify owners, and describe how upgrades are reviewed.
That is the difference between a local demo and an operated production component.
The practical decision is not whether an exporter is “better” than a database management platform. The practical decision is which operating model your team can actually sustain. If your platform already runs Prometheus-compatible observability, Oracle Database Metrics Exporter can be a strong fit. If your DBA team already operates Enterprise Manager or OCI Database Management as the production control plane, use the exporter as a complementary signal or do not add it until ownership is clear.
Schedule the readiness review before broad rollout. Bring the exact exporter version, image tag, /metrics output, enabled metric list, custom SQL, grant list, scrape configuration, dashboard draft, alert rules, runbook links, retention plan, and owner map.
Do not roll out broadly until each trust boundary has an owner.
]]>https://redstack.dev/2026/05/26/productionizing-oracle-database-metrics-exporter-least-privilege-private-scraping-and-operational-ownership/feed/04519From Graph Patterns To Analytics And Visualization
https://redstack.dev/2026/05/22/from-graph-patterns-to-analytics-and-visualization/
https://redstack.dev/2026/05/22/from-graph-patterns-to-analytics-and-visualization/#respondFri, 22 May 2026 13:12:00 +0000https://redstack.dev/?p=4434Continue reading →]]>GRAPH_TABLE is the right first tool because it demonstrates the core idea: match a graph pattern and return rows.
But graph work often goes one step further. You may want to rank important accounts, find connected groups, trace weighted paths, or visualize the network so a human can inspect it.
Article 3 used GRAPH_TABLE to find hubs, chains, cycles, and customer-risk joins. This article adds computed graph signals and visual exploration. You do not need a separate graph database after pattern matching; in-database algorithms and Graph Studio are the natural next step once you understand the graph.
Oracle gives you two practical next steps after basic pattern matching:
in-database graph algorithms with DBMS_OGA;
visual and notebook workflows in Graph Studio, backed by PGX for in-memory analytics.
Start With In-Database Algorithms
DBMS_OGA exposes graph algorithm functions that you can call from SQL. The function returns a temporary graph with computed properties, and GRAPH_TABLE reads those computed properties back as rows.
The syntax can look unusual at first, but the workflow is simple:
call the algorithm on BANK_GRAPH;
write the algorithm output to a vertex property;
query that output property with GRAPH_TABLE;
join the result to your relational tables.
Run the examples in this article in Autonomous Database Serverless on OCI if you want the algorithm examples to execute. At the time of writing, FreeSQL does not expose DBMS_OGA / DBMS_GAF, so the algorithm examples in this article will not work there.
If you are using ADB-S, run the setup from earlier articles first. Then check whether your database exposes the graph algorithm packages:
SELECT owner, object_name, object_type, status
FROM all_objects
WHERE object_name IN('DBMS_OGA','DBMS_GAF')
ORDERBY owner, object_name, object_type;
If that query does not show both packages, skip the DBMS_OGA examples in this article and move to the Graph Studio section.
The algorithm path depends on DBMS_OGA and DBMS_GAF. If those packages are not visible in your environment, keep using the earlier SQL property graph and GRAPH_TABLE examples, then move to the Graph Studio section.
If DBMS_OGA is visible, run demo/04_bank_graph_algorithms.sql. (The code is at end of this article). The script checks package visibility first, skips cleanly where the packages are absent, and uses the current schema when it builds the Bellman-Ford seed vertex JSON.
Treat these algorithm outputs as features, not verdicts. A PageRank score, component id, or path distance can help you prioritize work, but it should not be presented as proof of fraud. That distinction keeps the article technically useful without overstating what graph analytics can decide on its own.
The useful part is not just that the algorithm runs. It is that the computed graph output can come back through GRAPH_TABLE, become SQL rows, and join to the same relational context you already use.
PageRank: Which Accounts Are Structurally Important?
PageRank is a useful first centrality measure because it gives every vertex an importance score based on the graph structure.
In a bank-transfer graph, PageRank is not a fraud model. It is a signal. An account with high graph importance may deserve attention when combined with other context such as transfer amount, customer risk, device history, or known investigation seeds.
SELECT gt.account_id,
ba.account_name,
gt.pagerank_score
FROM GRAPH_TABLE(
DBMS_OGA.PAGERANK(
bank_graph,
PROPERTY(VERTEX OUTPUT pagerank_score),
20,
0.0001,
0.85,
TRUE
)
MATCH(a IS account)
COLUMNS (
a.account_id AS account_id,
a.pagerank_score AS pagerank_score
)
) gt
JOIN bank_accounts ba
ON ba.account_id = gt.account_id
ORDERBY gt.pagerank_score DESC;
Notice the same pattern from earlier articles. Even though an algorithm ran first, the output becomes SQL rows. That makes the score easy to sort, filter, join, or save.
You can also join the result back to customer or account data. For example, sort by PageRank and then show each account’s customer risk tier. The algorithm provides graph structure; SQL adds business context.
Weakly Connected Components: Which Accounts Belong Together?
Connected components find groups of vertices connected by edges. Weakly connected components treat directed edges as connected regardless of direction.
In a fraud investigation workflow, WCC is useful because it gives you a compact way to describe account clusters.
SELECT gt.component_id,
COUNT(*)AS account_count,
LISTAGG(ba.account_name,', ') WITHIN GROUP(ORDERBY ba.account_id)AS accounts
FROM GRAPH_TABLE(
DBMS_OGA.WCC(
bank_graph,
PROPERTY(VERTEX OUTPUT component_id)
)
MATCH(a IS account)
COLUMNS (
a.account_id AS account_id,
a.component_id AS component_id
)
) gt
JOIN bank_accounts ba
ON ba.account_id = gt.account_id
GROUPBY gt.component_id
ORDERBY account_count DESC, gt.component_id;
On a small graph, this may return one large component. That is fine. The useful pattern is the method: compute a graph-level grouping, then summarize it with SQL.
On a larger graph, connected components can help split an investigation into smaller clusters. They can also help you find isolated groups of accounts that do not interact with the rest of the network.
PageRank, Weakly Connected Components, and Bellman-Ford produce different kinds of graph features. Treat them as investigation inputs, not final decisions.
Bellman-Ford: Weighted Path Exposure
Bellman-Ford is a shortest-path algorithm. In a road network, the edge weight might be distance. In a transfer graph, the edge weight might be amount.
In this demo, a minimum cumulative transfer amount is not automatically a risk score. It is a path-based measure that may help investigation when paired with business rules.
The Bellman-Ford example starts from account 101 and uses transfer amount as the edge weight.
The seed vertex is account 101. The edge input property is amount, so the algorithm treats transfer amount as the path weight. The output property is minimum_transfer_exposure, which is then projected by GRAPH_TABLE and joined to bank_accounts.
This output is a weighted path signal from one starting account. In an investigation workflow, it could help you understand which accounts are reachable from a seed account under this weighting rule.
Move Into Graph Studio
SQL is enough to create and query the graph, but visualization helps beginners see what they built.
Graph Studio gives you a managed place to create, query, analyze, and visualize graphs in Autonomous AI Database. In this series, it is most useful for three things:
show BANK_GRAPH as a real graph object;
visualize a small subgraph around account 101;
run one notebook or query-panel example that mirrors the SQL article.
In Graph Studio, open the graph list, select BANK_GRAPH, and start with a small preview rather than the whole graph. Filter around account 101 or the 3-hop cycle so the visual reinforces the pattern queries instead of turning into a dense tangle.
If you use a notebook, run the same one-hop query from account 101 that you used in SQL. That helps connect the visual result back to the query:
SELECT*
FROM GRAPH_TABLE(
bank_graph
MATCH(src IS account)-[t IS transfer]->(dst IS account)
WHERE src.account_id =101
COLUMNS (
src.account_name AS source_account,
t.amount AS amount,
t.channel AS channel,
dst.account_name AS destination_account
)
)
ORDERBY amount DESC;
Where PGX Fits
PGX is Oracle’s in-memory graph analytics layer. It matters when you need richer algorithms, interactive analysis, notebook workflows, or high-performance graph analytics beyond the first SQL examples.
The practical path is incremental: start in SQL, add in-database algorithm signals when the packages are available, and move into Graph Studio or PGX when visualization or deeper analytics becomes useful.
That sequence keeps the mental model clean:
SQL property graph: define the graph over database objects.
GRAPH_TABLE: match graph patterns and return rows.
Graph Studio and PGX: visualize and analyze with a richer graph environment.
Where To Go Next
You now know how to recognize a graph-shaped problem, define a SQL property graph over relational tables, query connected patterns with SQL, join graph results to business context, and choose when to move into algorithms or visualization.
That is enough to start using graph features in real Oracle database work.
Try The Demo
This article has two demo paths.
For the algorithm path, use your own ADB-S instance. Run the setup steps below, then run the availability check and algorithm script. The script computes PageRank, Weakly Connected Components, and Bellman-Ford outputs, then returns the results as SQL rows.
For the FreeSQL path, stop before the algorithm script. FreeSQL is still useful for the table, graph, and GRAPH_TABLE pattern examples, but FreeSQL does not expose DBMS_OGA / DBMS_GAF.
After the SQL algorithm step, open Graph Studio in the same ADB-S environment and visualize a small part of BANK_GRAPH. Start with a filtered view around account 101 or the seeded transfer cycle. The goal is not to draw every relationship at once; it is to connect the SQL results back to a graph a person can inspect.
Here’s the code referenced above, which you can copy and paste into your environment. Please note that you need to run the set up steps 1 and 2 first, then step 4 – all are included below. If you followed the previous articles in this series, steps 1 and 2 are exactly the same code you ran in those articles. The code below contains comments that explains what it is doing.
-- Oracle AI Database 26ai graph demo
-- Step 1: create a tiny bank-fraud dataset.
--
-- Run this as a schema user that can create tables.
-- Start by removing objects from a previous run. The graph depends on the
-- tables, so it must be dropped before the tables can be recreated.
BEGIN
EXECUTEIMMEDIATE'DROP PROPERTY GRAPH bank_graph';
EXCEPTION
WHEN OTHERS THEN
-- Ignore cleanup errors so the script can be rerun from a fresh schema or
-- after dependencies have already been removed.
NULL;
END;
/
-- Drop the edge table before the vertex tables because it has foreign keys to
-- bank_accounts. ORA-00942 means the table did not exist, which is safe here.
]]>https://redstack.dev/2026/05/22/from-graph-patterns-to-analytics-and-visualization/feed/04434Hands-on: Run Oracle Database Metrics Exporter with Prometheus and Grafana
https://redstack.dev/2026/05/21/hands-on-run-oracle-database-metrics-exporter-with-prometheus-and-grafana/
https://redstack.dev/2026/05/21/hands-on-run-oracle-database-metrics-exporter-with-prometheus-and-grafana/#respondThu, 21 May 2026 13:30:00 +0000https://redstack.dev/?p=4498Continue reading →]]>This article uses Oracle Database Metrics Exporter 2.3.1, checked against Oracle’s documentation on 2026-05-10. Container image: container-registry.oracle.com/database/observability-exporter:2.3.1. Default listen address: :9161. Default metrics path: /metrics.
In the first article in this series, we looked at why application telemetry stops at the service boundary — and why a slow RAG endpoint or AI request often cannot be diagnosed without knowing what Oracle Database was doing at the same moment. This article turns that idea into a working local setup.
We’ll run Oracle Database Metrics Exporter against a development Oracle Database, scrape it with Prometheus, connect Grafana, and build the starter dashboard. By the end you’ll have panels showing exporter health, database reachability, sessions, activity, wait categories, and top SQL — all in the same time window as your application metrics.
Oracle’s docs and GitHub materials sometimes use Oracle AI Database Metrics Exporter where the product page uses Oracle Database Metrics Exporter. You may also see observability-exporter in the container image path. In this article, those references point to the same exporter.
The stack
The exporter sits between Oracle Database and Prometheus. It connects to the database, runs the metric queries, and exposes the results at /metrics. Prometheus pulls those metrics on a schedule. Grafana queries Prometheus to build panels.
Grafana does not connect directly to Oracle Database in this setup. That distinction matters when something goes wrong: if a panel is empty, the problem is almost always earlier in the chain. We’ll verify each link before moving to the next.
What you need
A development Oracle Database — local container, OCI Always Free, or a private lab instance
SQL admin access to create a monitoring user in the target PDB or service
With Oracle Database on the same Docker network, the exporter can reach it by container name. If Oracle Database is running on the host machine instead, use host.docker.internal as the hostname in the exporter connect string.
Create a monitoring user
The exporter needs its own database identity. Connect to the PDB or service you want to monitor and run:
SELECT_CATALOG_ROLE covers most of the default metrics without requiring a long list of individual view grants. It is a broad grant — convenient for a local demo, but not least-privilege for a shared environment. Narrowing this down is the main topic of the next article in this series.
With Oracle Database Free, the default PDB is FREEPDB1. Make sure you create the user in the service the exporter will connect to.
Configure the exporter
Create a local file with the connection details. Keep this file out of source control.
# exporter.env
DB_USERNAME=exporter_demo
DB_PASSWORD=<your_password>
DB_CONNECT_STRING=<host>:1521/<service-name>
Replace <host> with the address the exporter container can reach. If Oracle Database is another container on oracle-obs-demo, use its container name: for example, oracle-db:1521/FREEPDB1. If it’s running on the host, use host.docker.internal:1521/FREEPDB1.
That 1 means the exporter connected to Oracle Database and ran its queries successfully. If you see 0, the HTTP server is running but the database connection is not — check the connect string, service name, credentials, and whether the user exists in the right PDB. If the endpoint is unreachable, check docker ps and docker logs oracle-exporter.
Before moving on, take a quick look at what the exporter actually exposes:
curl-s http://localhost:9161/metrics | grep"^# HELP oracledb_" | head -20
This lists the metric names and descriptions for version 2.3.1. The PromQL queries in the sections below assume the default metric names from this version.
Add Prometheus
Create the scrape configuration:
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
-job_name: oracle-exporter
metrics_path: /metrics
static_configs:
-targets:
- oracle-exporter:9161
The target is oracle-exporter:9161 — the exporter’s container name on the Docker network. Prometheus will resolve that name from inside the network. Using localhost:9161 would point at the Prometheus container itself.
Open http://localhost:9090 and go to Status → Targets. The oracle-exporter job should show UP.
Confirm both signals in the query UI before continuing:
up{job="oracle-exporter"}
oracledb_up
up{job="oracle-exporter"} is whether Prometheus can scrape the exporter. oracledb_up is whether the exporter can reach Oracle Database. Both should return 1 before building any panels.
Add Grafana
docker run -d
--name grafana
--network oracle-obs-demo
-p127.0.0.1:3000:3000
"$GRAFANA_IMAGE"
Open http://localhost:3000 and log in. Default credentials for a fresh Grafana container are admin / admin.
Add Prometheus as a data source: Connections → Data sources → Add new data source → Prometheus. Set the server URL to:
http://prometheus:9090
Not http://localhost:9090 — Grafana is running inside Docker, where localhost means the Grafana container. Use the container name.
Save and test. When it shows connected, you’re ready to build panels.
Build the starter dashboard
Create a new dashboard. The panels below build from monitoring-chain health outward to database behavior. Start at the top and work down.
Is the monitoring chain working?
Two stat panels, side by side.
Prometheus → Exporter:
up{job="oracle-exporter"}
1 means Prometheus can scrape the exporter. 0 means the exporter is down or unreachable.
Exporter → Oracle Database:
oracledb_up
1 means the exporter has a working database connection. 0 means the exporter is alive but cannot reach the database.
These two panels separate the first layer of any debugging conversation: is the monitoring chain itself broken, or is the database the problem?
Exporter collection health
oracledb_exporter_last_scrape_error
Healthy value is 0. A nonzero value means the last collection had errors — often a permissions issue, a query timeout, or a broken custom metric configuration.
oracledb_exporter_last_scrape_duration_seconds
How long collection takes per scrape. If this climbs toward the scrape interval, the exporter is struggling to keep up — usually a slow query or high database load.
oracledb_exporter_scrapes_total
A running total of completed scrapes. Useful for confirming the exporter is actively collecting and not stalled.
Sessions
sum by (status, type) (oracledb_sessions_value)
Database sessions are not the same as active users. They include connection pool slots, background processes, and idle sessions. The useful question is not the absolute value — it is whether the shape changes at the same time as an application event. Did sessions spike when the slow request hit? Did inactive sessions accumulate after a deployment?
Activity
oracledb_activity_execute_count
oracledb_activity_parse_count_total
oracledb_activity_user_commits
oracledb_activity_user_rollbacks
These show whether the workload shape changed. A jump in execute or parse count often corresponds to a new query pattern, a connection pool opening more sessions, or a batch job starting. Compare them against application request volume on the same time axis.
The default Oracle activity metrics are gauges, not counters. Graph them directly. Only apply rate() after checking the # TYPE line for your exporter output.
Wait categories
oracledb_wait_time_user_io
oracledb_wait_time_system_io
oracledb_wait_time_concurrency
oracledb_wait_time_application
oracledb_wait_time_commit
oracledb_wait_time_network
Wait categories show where database time is going. They do not explain why a wait increased, but they tell you which direction to investigate next. User I/O rising with application latency is a different path than concurrency rising after a schema change.
The wait metrics are counters. For a rate-of-change view:
rate(oracledb_wait_time_commit[5m])
Top SQL
topk(10, oracledb_top_sql_elapsed)
This surfaces the SQL statements accumulating the most elapsed time. In a development setup it is the fastest way to find which query to look at next. The label set includes SQL identifiers and may include SQL text — useful locally, but worth reviewing before this panel goes into a shared dashboard.
Reading the dashboard
Once the panels are in place, run a real request through your application and watch the time window in Grafana.
Make a call to your RAG endpoint or Spring Boot AI service. During that window:
Did oracledb_sessions_value spike? Session pressure often shows up alongside connection pool wait time.
Did execute or parse count shift? More SQL activity usually means a different query pattern or a job running in parallel.
Did a wait category increase? User I/O rising with latency points toward reads. Concurrency rising points toward lock contention.
Did anything appear at the top of oracledb_top_sql_elapsed? That is the query to look at next.
The demo works. The question now is what it takes to run this reliably alongside a real application.
In the next article, we look at what productionizing the exporter actually requires: replacing the broad SELECT_CATALOG_ROLE grant with object-level grants for the metrics you enable, keeping the exporter endpoint private, reviewing which labels leave the database boundary, and making sure someone owns the component before it becomes a dependency nobody maintains.
]]>https://redstack.dev/2026/05/21/hands-on-run-oracle-database-metrics-exporter-with-prometheus-and-grafana/feed/04498Detect Fraud Patterns With Graphs
https://redstack.dev/2026/05/20/detect-fraud-patterns-with-graphs/
https://redstack.dev/2026/05/20/detect-fraud-patterns-with-graphs/#respondWed, 20 May 2026 13:17:00 +0000https://redstack.dev/?p=4409Continue reading →]]>We have tables. We have a SQL property graph named BANK_GRAPH. Now we can ask graph-shaped questions.
The key tool is GRAPH_TABLE.
GRAPH_TABLE is a SQL table expression. You give it a graph and a pattern to match, and it returns rows. That last part matters. Once the graph match becomes rows, you can use the rest of SQL: joins, filters, grouping, ordering, and common table expressions.
Article 2 created BANK_GRAPH. This article uses that graph to show why pattern matching is worth learning: it lets you express fraud questions about hubs, chains, and cycles more directly than equivalent join-heavy SQL, while still returning rows that join to customer risk data.
In this article, we will query four fraud-style patterns:
inbound hubs;
two-hop transfer chains;
transfer cycles;
graph results joined to customer risk data.
Before you start, you’ll need to run the setup code from Article 2. I have copied that here so you can do it all in the one place. Make sure you use the “Run Script” button so it runs all of the statements, not just the first one.
Then run this code:
Ok, now you have everything that we did in the previous two articles back in place!
Now here’s the code for this example:
If you prefer to run everything in ADB-S, copy those three scripts into the same schema and run them in order. SQLcl and SQL*Plus users can run the files directly from the command line.
Before looking at each query, notice the repeated shape. The graph pattern lives inside GRAPH_TABLE, and the rest of the statement is ordinary SQL. That split is the core habit to learn: use graph syntax to find connected structures, then use SQL to summarize and enrich the results.
Pattern 1: Inbound Hubs
A simple first fraud question is: which accounts receive the most transfers?
In graph terms, we are looking for transfer edges that point into the same destination account.
SELECT gt.account_id,
ba.account_name,
COUNT(*)AS inbound_transfers,
SUM(gt.amount)AS inbound_amount
FROM GRAPH_TABLE(
bank_graph
MATCH(src IS account)-[t IS transfer]->(dst IS account)
MATCH(src IS account)-[t IS transfer]->(dst IS account)
Read it from left to right: find an account vertex, follow a directed transfer edge, and land on another account vertex.
The COLUMNS clause chooses which graph properties become SQL columns. Here we project the destination account id and transfer amount. The outer SQL query groups those rows to find inbound hubs.
For the demo data, account 105 should stand out because several transfers point into it. That result is not automatically suspicious, but it is a useful triage signal. In a real system, you would combine it with time windows, amount thresholds, customer risk, and historical behavior.
Pattern 2: Accounts In The Middle
A second question is more interesting: which accounts sit in the middle of two-hop money movement?
This is where graph syntax starts to feel natural. You are not mentally building a chain of self-joins. You are drawing the relationship pattern and asking Oracle to return the matches.
This query also shows why aliases matter. src, mid, and dst are not table names. They are pattern variables. The same account label appears three times, but each occurrence has a different role in the path. Good variable names make graph patterns much easier to explain on screen.
Pattern 3: Transfer Cycles
Fraud investigations often care about circular movement. Money leaves one account, moves through other accounts, and eventually returns.
The demo data has a simple cycle:
101 -> 102 -> 103 -> 101
In graph terms, we want to start at an account and return to the same account after a few transfer hops.
SELECT gt.account_id,
ba.account_name,
COUNT(*)AS cycle_count
FROM GRAPH_TABLE(
bank_graph
MATCH(a IS account)-[IS transfer]->{3,5}(a)
COLUMNS (
a.account_id AS account_id
)
) gt
JOIN bank_accounts ba
ON ba.account_id = gt.account_id
GROUPBY gt.account_id, ba.account_name
ORDERBY cycle_count DESC, gt.account_id;
The {3,5} quantifier is the part to notice. It asks for paths of three to five repetitions of the transfer step. The final (a) says the path must return to the same starting account.
The graph query expresses the business question almost exactly: “find accounts that can reach themselves through three to five transfers.”
Pattern 4: Join Graph Results To Customer Risk
Graph results are useful by themselves, but they become much more useful when you join them to business context.
For example, a cycle involving a low-risk account may be less urgent than a cycle involving a high-risk customer. Because GRAPH_TABLE returns rows, we can join cycle results to bank_accounts and customers.
This is one of the strongest reasons to learn graph inside Oracle Database. You do not have to choose between graph analysis and relational context. You can combine them in one SQL workflow.
That is the practical payoff of this article. GRAPH_TABLE does not trap you in a graph-only world. It gives you a row source. Once you have rows, the rest of your SQL skills still apply.
What To Watch For
Graph syntax makes connected questions easier to read, but it does not remove the need for careful modeling.
Use stable keys for vertices and edges. Expose only the properties readers or applications need. Keep labels clear. Make edge direction explicit. If your business question treats relationships as undirected, say that clearly and choose the right query or algorithm path.
Next Step
Pattern matching answers many practical questions. But sometimes you want a computed signal: an importance score, a connected group id, or a weighted distance from a seed account.
That is where in-database graph algorithms come in. The next article uses DBMS_OGA in ADB-S, because the tested FreeSQL environment does not expose the algorithm packages. It then moves the same graph into Graph Studio for visualization.
That is also where edge weights become concrete. In the next article, the amount property on a transfer edge becomes the weight for a path example, instead of remaining an abstract graph term.
Try The Demo
The hands-on part of this article is the pattern-query script. It uses the BANK_GRAPH you created in Article 2 and runs the four query families you just learned:
inbound hubs;
two-hop transfer chains;
transfer cycles;
graph results joined to customer risk.
Use the embedded FreeSQL runner near the top of the article for the quick path. If you prefer ADB-S, run the same script in the schema where BANK_GRAPH already exists.
When the script finishes, spend a minute with the output instead of rushing ahead. Look for account 105 in the inbound hub result, the middle-account counts in the two-hop result, and the medium/high-risk customers in the hybrid query. Those outputs are the bridge between graph pattern matching and the algorithm examples in the next article.
]]>https://redstack.dev/2026/05/20/detect-fraud-patterns-with-graphs/feed/04409Add real business actions to your Spring AI app with Oracle (part 3 of 4)
https://redstack.dev/2026/05/19/add-real-business-actions-to-your-spring-ai-app-with-oracle-part-3-of-4/
https://redstack.dev/2026/05/19/add-real-business-actions-to-your-spring-ai-app-with-oracle-part-3-of-4/#commentsTue, 19 May 2026 12:37:20 +0000https://redstack.dev/?p=4401Continue reading →]]>By the end of Episode 2, the assistant could answer policy questions from Oracle Vector Store and remember conversations across requests. That combination already felt more like a real application than a bare LLM wrapper.
But it still could not act on anything.
Ask it about order ORD-1002 and it would explain the shipping policy. It could not look up the actual order. Ask it to return a product and it would describe the return process. It could not initiate the return. The knowledge was there. The memory was there. The connection to the backend was not.
Before looking at the code, it is worth being precise about what tool calling is and what it is not.
The model does not get direct access to the database. It does not write SQL. It does not update rows. What it gets is the ability to request that the backend perform a specific named action. The backend then decides whether to allow it, validates the input against business rules, performs the operation if allowed, and returns a result. The model reads that result and generates a response.
This is the difference between AI orchestration and AI autonomy. The model orchestrates. The backend decides. That distinction is what makes the system trustworthy rather than unpredictable.
What changes
The architecture from Episode 2 carries forward unchanged. The memory advisor, the vector-store advisor, and the Oracle-backed persistence are all still there. The only additions are one tool class, one new entity, and one line in ChatClientConfig.
defaultTools(agentTools) registers the AgentTools bean with the chat client. From that point, the model knows those tools exist and can request them during any conversation.
The system prompt was also updated to tell the model how to use the tools and to reinforce that tool results are authoritative:
app:
assistant:
system-prompt:>
You are ShopAssist, a concise and practical support assistant for a demo
electronics store. Use retrieved policy context when it is available.
Use tools for order status lookup, return initiation, and support ticket
creation. Treat tool results as the source of truth for business actions
and explain validation failures clearly. Do not invent order details.
Do not invent action outcomes.
The tool class
AgentTools.java contains three methods, each annotated with @Tool. That annotation is what exposes the method to the model. Spring AI reads the description and parameter annotations at startup and includes them in the model’s context so it knows what each tool does and when to use it.
@Tool(description="Look up the current status and basic details for a ShopAssist order.")
@Transactional(readOnly=true)
publicStringlookupOrderStatus(
@ToolParam(description="The ShopAssist order ID, for example ORD-1002.")StringorderId
){ ... }
@Tool(description="Initiate a return for an eligible delivered ShopAssist order after backend validation.")
@Transactional
publicStringinitiateReturn(
@ToolParam(description="The ShopAssist order ID, for example ORD-1001.")StringorderId,
@ToolParam(description="The customer's reason for the return.")Stringreason
){ ... }
@Tool(description="Create a support ticket for an existing ShopAssist order.")
@Transactional
publicStringcreateSupportTicket(
@ToolParam(description="The ShopAssist order ID, for example ORD-1002.")StringorderId,
@ToolParam(description="A short description of the customer issue.")Stringissue,
@ToolParam(description="Ticket priority such as LOW, NORMAL, HIGH, or URGENT.",required=false)Stringpriority
){ ... }
The return types are all String. That is intentional — plain text results are easy for the model to summarise naturally without needing to parse structured data.
lookupOrderStatus is marked @Transactional(readOnly = true). initiateReturn and createSupportTicket are @Transactional because they write to Oracle. The transaction boundary sits inside the tool method, so a validation failure exits cleanly without any partial database change.
How a tool call actually flows
When the model decides a tool is needed, it does not generate a response immediately. Instead it emits a structured tool-call request back to the application. Spring AI intercepts that, invokes the matching method, and sends the result back to the model as a tool message. The model then generates its final response with the result in context.
The full round trip for a return request looks like this: the user message arrives, the memory advisor loads conversation history, the vector-store advisor retrieves relevant policy documents, the model sees all of that and decides to call initiateReturn, the backend validates and either updates Oracle or returns a failure reason, and the model then writes the response to the user based on what the backend actually said.
Business rules in the backend
The return validation is worth looking at directly because it is the clearest example of the backend owning business policy:
return"Return initiated for order %s. The order status is now %s."
.formatted(order.getOrderId(),order.getStatus());
}
Four checks in sequence: already returning, not yet delivered, outside the 30-day window, then success. Every failure exits early with a plain-text reason and touches nothing in the database. Only the last path calls customerOrderRepository.save().
The markPreparingReturn() call is a domain method on CustomerOrder. The status change lives on the entity, not scattered across service or tool layers.
The support ticket entity
SupportTicket is a simple JPA entity backed by the SUPPORT_TICKET table. Episode 3 adds it with Hibernate’s ddl-auto=update creating the table on first startup — no migration script.
The key ID uses GenerationType.SEQUENCE with an explicit @SequenceGenerator, which is the recommended Oracle pattern. Priority and status are plain strings rather than enums — the tool normalises whatever the model passes and defaults anything unrecognised to NORMAL.
Trying it
The application seeds four deterministic demo orders on startup: ORD-1001 (delivered, within the 30-day return window), ORD-1002 (shipped), ORD-1003 (delivered, outside the return window), and ORD-1004 (processing).
Order lookup:
curl-s-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"What is the status of order ORD-1002?"}' | jq
The assistant calls lookupOrderStatus, reads the live status from Oracle, and returns it. It does not guess or interpolate from the conversation.
Successful return:
curl-s-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"I want to return order ORD-1001 because the product was defective."}' | jq
The backend finds the order, confirms it is delivered and within the return window, calls markPreparingReturn(), and saves to Oracle. The status in CUSTOMER_ORDER is now PREPARING_RETURN.
Failed return:
curl-s-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"I want to return order ORD-1003 because the product was defective."}' | jq
ORD-1003 was delivered 45 days ago. The backend rejects it at the return-window check and returns a clear reason. Nothing is written to the database. The model relays the rejection to the user.
This failure case is as important as the success case. It demonstrates that the model cannot bypass business rules by asking politely.
Support ticket:
curl-s-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"Create a high-priority support ticket for ORD-1002 because shipping is stuck."}' | jq
The backend verifies the order exists, normalises the priority to HIGH, sets status to OPEN, and inserts a row into SUPPORT_TICKET.
Inspecting Oracle directly
After those four requests, you can see the backend state directly:
SELECT ORDER_ID, STATUS FROM CUSTOMER_ORDER;
ORD-1001 now shows PREPARING_RETURN. The other three are unchanged.
SELECT TICKET_ID, ORDER_ID, PRIORITY, STATUS FROM SUPPORT_TICKET;
One row: the high-priority ticket for ORD-1002.
The assistant is useful because it is connected to real application state. Not because the model became more capable.
Oracle is now storing four kinds of data
Episode 1 added relational order data and vector embeddings. Episode 2 added conversational state. Episode 3 adds support ticket rows written by tool calls.
All four live in the same Oracle database: CUSTOMER_ORDER, the vector store table, SPRING_AI_CHAT_MEMORY, and SUPPORT_TICKET. Still one database connection from the application. No additional infrastructure.
What is next
The application can now retrieve knowledge, remember conversations, and perform backend actions. But everything still happens synchronously inside a single HTTP request. The model calls a tool, waits for the result, and then responds.
That works for simple actions. It does not work for anything that takes time, depends on external systems, or needs to be retried. Episode 4 starts moving toward event-driven processing — work that can happen outside the request cycle and feed back into the conversation when it completes.
]]>https://redstack.dev/2026/05/19/add-real-business-actions-to-your-spring-ai-app-with-oracle-part-3-of-4/feed/14401From Oracle Database to Grafana: What Oracle Database Metrics Exporter Does for Developers
https://redstack.dev/2026/05/18/from-oracle-database-to-grafana-what-oracle-database-metrics-exporter-does-for-developers/
https://redstack.dev/2026/05/18/from-oracle-database-to-grafana-what-oracle-database-metrics-exporter-does-for-developers/#commentsMon, 18 May 2026 17:55:34 +0000https://redstack.dev/?p=4463Continue reading →]]>Freshness note: At the time of writing, the current exporter release is 2.3.1, the default listen address is :9161, the default telemetry path is /metrics, and container examples use container-registry.oracle.com/database/observability-exporter:2.3.1. Treat these as version-specific details and recheck current documentation before relying on copy/paste commands.
Application telemetry stops too early
A Spring Boot AI service can look healthy in the places developers check first. The HTTP layer reports normal error rates. Application metrics show request latency, JVM behavior, token timing, and maybe HikariCP connection pool usage. Then a retrieval-augmented generation, or RAG, endpoint slows down, and the only obvious clue is that “the database call took longer.”
That clue is too thin when Oracle Database is part of the user experience. The database may hold vectors, JSON documents, relational records, queues, conversation state, ingestion metadata, and application state. A slow answer might come from a code change in the service, a different retrieval query, an ingestion job competing with search traffic, a session spike, a wait-class shift, or a SQL hotspot.
Application telemetry is necessary, but it often stops at the application boundary. Database-side metrics fill a different gap: they show what the database was doing during the same time window as application latency, pool pressure, model calls, deployments, and workload changes.
Oracle Database Metrics Exporter exposes Oracle Database metrics so observability tools can scrape, store, visualize, and alert on database behavior alongside application behavior. The payoff is not another dashboard for its own sake. The payoff is correlation by workflow: when a RAG endpoint slows down, developers and platform teams can inspect database-side signals in the same timeline as the service that depends on them.
What a database exporter does
A database exporter is a small service that connects to a database, collects selected metrics, and exposes those metrics through an endpoint that monitoring systems can scrape.
That definition matters because an exporter is a bridge, not the destination. It is not the database. It is not Grafana. It is not an application metrics library. It is not a trace collector. Its job is to turn database-side signals into input for the observability pipeline you already use.
In a Prometheus-style setup, the monitoring system usually follows a pull model. Prometheus or another compatible scraper periodically requests metrics from a target endpoint. The exporter is that target. It connects to Oracle Database, collects configured metrics, and exposes them over HTTP in a scrapeable format.
That changes the debugging conversation. Instead of asking for a separate database view after the fact, the application team can start with a shared timeline: request latency rose at 10:05, connection pool wait time rose at 10:06, sessions increased at 10:06, and database wait behavior changed at 10:07. Metrics do not finish the diagnosis, but they tell everyone where to look next.
What Oracle Database Metrics Exporter is
Tthe exporter is a bridge between Oracle Database instances and observability tools. The exporter exposes metrics in a format compatible with Prometheus-style scraping. metrics are OpenTelemetry and Prometheus-compatible. This article focuses on the Prometheus path because it is the most direct path to reason about: the exporter exposes metrics over HTTP, Prometheus or a compatible scraper collects and stores them, and Grafana visualizes them through a Prometheus-compatible data source.
In an OpenTelemetry-oriented platform, a common pattern is to use the OpenTelemetry Collector as part of the metrics pipeline, for example by scraping the exporter’s Prometheus-format endpoint with the Collector’s Prometheus receiver and forwarding metrics to a backend. That does not mean the exporter emits traces, performs automatic application-to-database trace correlation, or natively pushes OTLP metrics to every backend.
The exporter project is free and open source. It is available under your choice of the Universal Permissive License v1.0, or the MIT license . That statement applies to the exporter project itself; database, infrastructure, cloud service, managed backend, and SaaS observability costs are separate.
The exporter works across on-premises, cloud, Kubernetes, single-instance, clustered, and Autonomous Database deployments. Check the current docs for exact version, network, authentication, wallet, and privilege requirements in your environment.
The exporter can provide default metrics and custom SQL-based metrics defined in YAML or TOML. Custom metrics are powerful, but they need design review. Each query needs appropriate database grants and should be evaluated for execution cost, scrape interval, timeout behavior, label cardinality, and sensitive data exposure.
The path from Oracle Database to Grafana
Grafana is not collecting from Oracle Database directly in this path. The usual flow looks like this:
The default endpoint details are version-specific. In version 2.3.1, the exporter defaults to --web.listen-address=:9161 and --web.telemetry-path="/metrics".
The networking detail that trips up many first demos is point of view. Use the address reachable from Prometheus, not necessarily the address reachable from your terminal. For a same-host local test, this might be localhost:9161. In Docker Compose, localhost usually means the Prometheus container itself, so the target is usually the exporter service name. In Kubernetes, it would normally be a Service DNS name.
For a same-host local test where Prometheus can reach the exporter on localhost, the scrape target might look like this:
scrape_configs:
-job_name:"oracle-database"
static_configs:
-targets:["localhost:9161"]
For a Docker Compose-style setup where exporter is the service name reachable from the Prometheus container, the target would look more like this:
scrape_configs:
-job_name:"oracle-database"
static_configs:
-targets:["exporter:9161"]
These snippets show the shape of the scrape configuration, not a complete production Prometheus setup. The correct target depends on where Prometheus runs, how the exporter is exposed, and what network rules sit between the scraper and the exporter.
A first useful local check
The smallest useful demo is not a full dashboard. It is proving that the exporter can connect to a development database and expose one expected metric.
Oracle provides a local Docker Compose test stack with Oracle AI Database, the exporter, Prometheus, and Grafana, and the docs state that it provisions a dashboard. Treat that stack as local testing only. Do not expose sample database listener ports on shared or public hosts.
You can start up the demo system with a command like this – make sure you choose a password, don’t copy the example:
cd docker-compose
DB_PASSWORD='<choose-a-local-demo-password>' docker-compose up -d
Once the exporter is running and reachable from your shell, the first check is simple:
This proves that the exporter can observe the database from its own connection path. It does not prove application health, production readiness, or that every metric query succeeded. If oracledb_up is missing or zero, check exporter logs, database connectivity, credentials, privileges, service name, and metric configuration before trusting deeper panels.
You can log into the Grafana instance at http://localhost:3000 and you will need to enter “admin” as both the user and the password. It will ask you to create a new password. Then you can nagivate to “Dashboards” and open the “Oracle Dashboard”. You’ll see something like this:
What to look at first
Start with exporter health before interpreting database behavior. The default metrics include oracledb_exporter_last_scrape_error, oracledb_exporter_last_scrape_duration_seconds, and oracledb_exporter_scrapes_total.
A healthy oracledb_exporter_last_scrape_error value is 0. A nonzero value indicates exporter scrape errors, not necessarily a database outage. The cause might be credentials, network reachability, a timeout, a permissions problem, a custom metric query, or database load.
Then add a few database-side panels that help explain application symptoms.
oracledb_up is the basic availability signal from the exporter’s perspective:
oracledb_up
For sessions, Oracle’s 2.3.1 sample output shows oracledb_sessions_value with labels such as status and type, so this is a reasonable first query after validating your own output:
sum by (status, type) (oracledb_sessions_value)
Do not treat this as a direct count of active users. Database background sessions and configuration can make the result noisy. The useful question is whether the shape changes during the incident window: did sessions rise when the endpoint slowed down, did inactive sessions pile up, or did work shift after a deployment or ingestion job?
Activity metrics such as oracledb_activity_execute_count, oracledb_activity_parse_count_total, oracledb_activity_user_commits, and oracledb_activity_user_rollbacks can show whether workload changed. Graph activity metrics directly first. Only use rate() after confirming the metric type and behavior in the exporter output for your version, because the docs expose some cumulative-looking database activity values as gauges.
Wait-time metrics provide another useful triage layer. Default metrics include categories such as user I/O, system I/O, concurrency, application, commit, and network:
oracledb_wait_time_user_io
oracledb_wait_time_system_io
oracledb_wait_time_concurrency
oracledb_wait_time_application
oracledb_wait_time_commit
oracledb_wait_time_network
In the demo environment, there is probably not enough workload to see waits. In a real system, the value is in watching whether wait behavior changes during the same window as application latency.
The default metrics also include oracledb_top_sql_elapsed. Use it as a hotspot signal, not as a complete tuning workflow. In the sample, this metric includes labels such as SQL ID and truncated SQL text. That can be useful for triage, but it also raises label-cardinality and sensitive-text concerns. Review whether those labels are appropriate for your monitoring backend before enabling broad retention or alerting on them. You may not want all your SQL statement being stored in your monitoring backend!
Why AI applications make database metrics part of user experience
AI applications often make database behavior more visible to users, even when the application code hides the details. A RAG endpoint might perform vector search, filter JSON metadata, fetch relational records, update conversation memory, write audit rows, and call a model in a single request path. If one of those database steps slows down, the user experiences it as a slow answer.
Application metrics can show that the endpoint got slower. They may also show that the connection pool waited longer or that model latency was stable. But they usually cannot answer database-side questions by themselves:
Did sessions rise during ingestion? Did execute or parse activity change after a new retrieval strategy? Did waits move toward I/O, concurrency, commit, network, or application categories? Did a new SQL shape become a hotspot? Did the exporter itself start reporting scrape errors?
Oracle Database Metrics Exporter helps answer those questions in the same observability workspace used for service metrics. That does not make the exporter an AI-specific tool. It makes it useful for AI systems because AI request paths often combine application code, database retrieval, background ingestion, and model calls in ways that are difficult to debug from one layer alone.
Security basics before copy/paste becomes habit
The exporter needs database connectivity and credentials. For demos, environment variables are acceptable placeholders. For production-like setups, use configuration files, password files, vault integrations, wallet-based authentication, or platform secret management as appropriate.
There are several credential and authentication options, including username/password, environment-variable substitution, password files, OCI Vault, Azure Vault, HashiCorp Vault, Oracle Wallet with TLS or mTLS, Secure External Password Store, and external authentication. For mTLS connections, including Autonomous Database with mTLS, Oracle Wallet is required.
Privileges deserve the same care. For default metrics, the documentation lists SELECT_CATALOG_ROLE as one option and also lists object-level grants on specific catalog and dynamic performance views. Do not treat SELECT_CATALOG_ROLE as automatically least privilege. In production-like environments, create a dedicated monitoring user and grant the narrowest permissions that support the metrics you actually collect. For custom metrics, grant access only to the objects queried by those metrics.
Tune scrape interval and query timeout for your environment. Metric collection is database work. Its cost depends on the default metrics you enable, custom SQL, scrape frequency, query timeout, number of databases, network latency, and current database load. You should be aware that running the exporter is not “zero overhead” or “low overhead” – it depends on the metrics you define and how often you collect them. You should perform measurement in your own environment.
Network placement also matters. The exporter must reach the database listener. Prometheus or the OpenTelemetry Collector must reach the exporter endpoint. Grafana must reach the metrics backend, not necessarily the exporter. In production, keep database listeners and exporter endpoints inside the intended network boundary and expose only what your monitoring architecture requires.
How it fits with tools you already have
Oracle Database Metrics Exporter complements application telemetry; it does not replace it. Spring Boot Actuator and Micrometer show how the application experiences the database: connection pool wait time, request latency, error rates, JVM behavior, and application-specific counters. The exporter shows database-side signals. The useful workflow is to compare both in the same time window.
It also does not replace Oracle Enterprise Manager or deeper Oracle diagnostic workflows. Enterprise Manager remains a broader Oracle management and monitoring platform. Exporter metrics are a different integration primitive: a bridge into Prometheus-compatible developer and SRE metrics workflows.
For detailed SQL tuning, plan changes, workload analysis, and deeper database diagnosis, use the appropriate Oracle diagnostic tooling and DBA workflows, subject to your edition and licensing. Metrics can tell you where to look. They do not automatically explain every query plan, locking issue, schema design problem, or workload pattern.
The exporter path is most relevant when Prometheus-compatible metrics are the standard integration layer, or when platform teams want Oracle Database behavior available in the same metrics pipeline as the rest of their services.
Custom SQL collectors can also be useful, especially for application-specific signals. The tradeoff is that you own the query design, metric naming, labels, metric types, privileges, scrape endpoint, and operational behavior. A maintained database exporter reduces the need to build every one of those pieces from scratch.
The practical mental model
Think of Oracle Database Metrics Exporter as a narrow but valuable bridge:
Oracle Database behavior
→ exporter metric queries
→ scrapeable metrics endpoint
→ Prometheus-compatible storage
→ Grafana panels, alerts, and shared incident timelines
That bridge is useful because database behavior often explains application symptoms. It is especially useful for AI applications, where one slow response may involve retrieval queries, JSON filters, vector search, ingestion load, connection pools, and model calls.
Start small. Prove oracledb_up. Check exporter scrape health. Add one sessions panel. Add one activity or wait panel. Compare those panels against application latency during a real workload. Once the database appears in the same timeline as the application, the conversation changes from “the database was slow” to “here is what changed, when it changed, and where we should investigate next.”
]]>https://redstack.dev/2026/05/18/from-oracle-database-to-grafana-what-oracle-database-metrics-exporter-does-for-developers/feed/24463Build Your First SQL Property Graph In Oracle AI Database 26ai
https://redstack.dev/2026/05/15/build-your-first-sql-property-graph-in-oracle-ai-database-26ai/
https://redstack.dev/2026/05/15/build-your-first-sql-property-graph-in-oracle-ai-database-26ai/#commentsFri, 15 May 2026 15:42:00 +0000https://redstack.dev/?p=4381Continue reading →]]>The first article introduced the graph idea: vertices are things, edges are relationships, and properties describe both.
Now we will build one.
The easiest way to learn SQL property graphs in Oracle AI Database 26ai is to start with ordinary tables. That keeps the graph concrete. You can see the rows first, then see how the graph definition gives those rows a connected shape.
The point of this article is simple: you can create a queryable fraud graph on top of existing Oracle tables in one SQL statement, without duplicating the underlying data. By the end, you will have run the seed SQL, created BANK_GRAPH, and inspected the metadata Oracle stores for the graph.
In this article, we will create a small bank dataset and define a graph named BANK_GRAPH.
Start With Tables, Not Theory
Our fraud example has three tables:
customers, which stores customer names and risk tiers;
bank_accounts, which stores account records;
bank_transfers, which stores money movement from one account to another.
The transfer table is the key. Every transfer has a source account and a destination account. That is already an edge hiding in relational form.
This is why the example works well for a first graph. We do not have to invent a relationship. The relationship already exists in the schema; the graph definition just makes it explicit and queryable as a path.
The demo seed data includes a few useful patterns:
a 3-hop cycle: 101 -> 102 -> 103 -> 101;
a fan-in pattern where several accounts send money to account 105;
a two-hop chain where account 105 sends to 108, and 108 sends to 106;
customer risk tiers that we can join back to graph results later.
First, create the three tables, load the small dataset, and print row counts. Make sure you flip the switch to enable read/write so you can create new objects! If you do not, you will get an “insufficient privileges” error.
If you prefer to work in your own Autonomous Database Serverless instance, copy the same script into SQL Worksheet and run it there. SQLcl and SQL*Plus users can run the file directly from the command line.
When it finishes, you should see row counts for customers, accounts, and transfers.
This first tutorial deliberately avoids Object Storage and bulk-loading APIs. Those matter for production data, but they add noise to a beginner lesson whose real goal is graph modeling.
Define The Graph Vocabulary
The graph definition answers four questions:
Which table contains vertices?
Which table contains edges?
Which columns identify each vertex and edge?
Which properties should graph queries expose?
For this demo, bank_accounts becomes the vertex table and bank_transfers becomes the edge table.
The VERTEX TABLES clause says that rows in bank_accounts are account vertices. The KEY clause says account_id uniquely identifies each vertex.
The EDGE TABLES clause says that rows in bank_transfers are transfer edges. The SOURCE KEY and DESTINATION KEY clauses make the edge direction explicit.
That direction matters. A transfer from account 101 to account 102 is not the same as a transfer from 102 to 101.
The PROPERTIES clauses are equally important. They decide which table columns are visible to graph queries. If you leave a column out, it remains available to ordinary SQL, but it will not be projected as a graph property in the graph pattern. For a teaching demo, keep the exposed properties small and obvious.
Next, create BANK_GRAPH and run the metadata checks shown below.
If you are using ADB-S instead, copy the code into the same schema where you ran the seed script.
Inspect The Graph
After the graph is created, inspect the database metadata.
The first check is simple:
SELECT graph_name
FROM user_property_graphs
WHERE graph_name ='BANK_GRAPH';
That confirms that Oracle Database knows about the graph object.
You should see the account vertex element and the transfer edge element.
Then inspect labels and properties. This is useful when you are teaching or debugging because it shows the vocabulary that graph queries can use.
SELECT graph_name, label_name, property_name
FROM user_pg_label_properties
WHERE graph_name ='BANK_GRAPH'
ORDERBY label_name, property_name;
The output should include properties such as ACCOUNT_ID, ACCOUNT_NAME, BALANCE, AMOUNT, CHANNEL, and TRANSFER_TS.
This metadata check is more than a sanity test. If a later graph query cannot see amount or account_name, the metadata views tell you whether the graph definition exposed those properties in the first place.
What The Graph Does Not Do
Creating BANK_GRAPH does not change the purpose of the base tables. Applications can still use customers, bank_accounts, and bank_transfers as ordinary relational tables.
The graph also does not decide what is fraudulent. It gives you a way to ask connected-data questions. In later articles, those questions become signals: cycles, hub accounts, accounts in the middle of transfer chains, PageRank scores, and connected groups. A real fraud workflow would combine those signals with business rules, investigation history, KYC data, device information, and human review.
The graph helps you see connection patterns. It does not magically replace risk modeling.
A Quick Check Before Moving On
Before you continue, make sure three things are true.
First, the base tables have rows. Second, USER_PROPERTY_GRAPHS shows BANK_GRAPH. Third, USER_PG_LABEL_PROPERTIES shows the properties you expect to query later, especially ACCOUNT_ID, ACCOUNT_NAME, AMOUNT, CHANNEL, and TRANSFER_TS.
Those checks are small, but they save time. Most beginner graph-query mistakes come from one of two places: the graph object was not created in the schema you are querying, or the property you want was not exposed in the graph definition.
If those checks pass, we can focus on patterns instead of setup. That is exactly where graph starts to feel different from ordinary table queries in practice.
Why This Matters
The graph is now ready, but the original data has not stopped being relational data.
That is the point. You can still query customers, bank_accounts, and bank_transfers with ordinary SQL. The graph adds a new query surface for connected patterns.
In the next article, we will use GRAPH_TABLE to ask questions like:
Which accounts receive money from many sources?
Which accounts sit in the middle of transfer chains?
Which accounts are part of transfer cycles?
Which suspicious graph results belong to high-risk customers?
Those questions are where the graph model starts to pay off.
Next step: move to Article 3, where the graph stops being metadata and starts answering fraud questions.
Try The Demo
This article had two runnable moments that you already saw above!
First, load the small bank dataset. That gives you ordinary relational tables with customers, accounts, and transfers. Second, create BANK_GRAPH over those tables and inspect the graph metadata.
Use the embedded FreeSQL runners above if you want the fastest path. Step 1 loads the data; Step 2 creates and checks the graph. If you prefer to use your own ADB-S instance, copy the same SQL into SQL Worksheet and run the scripts in the same order.
When both steps finish, you should have a graph named BANK_GRAPH in your schema. Keep it there for the next article. We will use that same graph to query hubs, two-hop chains, cycles, and customer-risk joins.
]]>https://redstack.dev/2026/05/15/build-your-first-sql-property-graph-in-oracle-ai-database-26ai/feed/14381Add persistent chat memory to your Spring AI chatbot with Oracle (part 2 of 4)
https://redstack.dev/2026/05/15/add-persistent-chat-memory-to-your-spring-ai-chatbot-with-oracle-part-2-of-4/
https://redstack.dev/2026/05/15/add-persistent-chat-memory-to-your-spring-ai-chatbot-with-oracle-part-2-of-4/#respondFri, 15 May 2026 12:28:44 +0000https://redstack.dev/?p=4392Continue reading →]]>The first version of this application could already answer support questions against real policy data. Oracle Vector Store was retrieving the right documents before generation, and the responses were grounded in what was actually in the database rather than in whatever the model happened to know from training.
But every request started from zero.
Send “My name is Maya” and then immediately ask “What’s my name?” and the assistant had no idea. Not because retrieval failed. Because the application itself was stateless. Conversation history was never stored anywhere. Each request arrived with only the current message and the policy documents that matched the similarity search. The moment the response was sent, everything about the exchange was gone.
That is the gap between a search engine with a chat interface and something that actually behaves like a conversation. Episode 2 closes it. Watch it here,
RAG and memory are different problems
It is worth being precise about this before looking at the code, because the two ideas are easy to conflate.
RAG — retrieval-augmented generation — gives the model access to information it would not otherwise have. When a customer asks about the refund policy, the application runs a similarity search against Oracle Vector Store, finds the relevant policy document, and includes it in the prompt. The model can then answer from real data rather than from training knowledge.
Conversational memory is a different thing entirely. It is not about what the model knows. It is about what the application remembers. Without memory, each request is independent. With memory, the application accumulates context across exchanges — facts the user has shared, questions already asked, decisions already made — and makes that context available to the model on every subsequent request.
Both matter. RAG makes individual answers accurate. Memory makes the conversation coherent. Episode 1 solved the first problem. Episode 2 solves the second.
What changes
The overall architecture stays the same. Spring Boot, Spring AI, Oracle Vector Store, and OpenAI are all unchanged from Episode 1. The only addition is persistent chat memory backed by a JDBC repository in Oracle.
MessageWindowChatMemory keeps a sliding window of the most recent messages per conversation. The window size is maxMessages, set to 100 in application.yml. As the conversation grows, older messages fall off the window so the prompt does not grow without bound.
The @ConditionalOnMissingBean annotation is worth noting. Tests substitute an in-memory ChatMemory implementation in TestSupportConfiguration, so the test suite can load the full application context without requiring a live database. The @ConditionalOnMissingBean is what makes that substitution work — if a test has already registered a ChatMemory bean, this bean definition is skipped.
Adding memory to the chat client
Episode 1 already had a QuestionAnswerAdvisor wired into the ChatClient for RAG retrieval. Episode 2 adds MessageChatMemoryAdvisor in front of it:
The order matters, and it is worth understanding why.
Advisors in Spring AI form a chain that wraps around the model call. Each advisor can modify the request before it reaches the model and can inspect or modify the response on the way back out. They execute in registration order on the way in, and in reverse order on the way out.
Registering MessageChatMemoryAdvisor first means it runs before QuestionAnswerAdvisor. On the way in, the memory advisor loads the stored conversation history for the current conversation ID and adds those messages to the request. By the time QuestionAnswerAdvisor runs its similarity search, the full conversation context is already present. The retrieved policy documents are then appended on top of that. By the time the model sees the request, it has both the conversation history and the relevant policy knowledge.
If the advisors were in the wrong order — retrieval first, memory second — the memory advisor would add conversation history after retrieval had already run. That would still work for basic memory, but the similarity search would only have the current message to work with, not the full conversation context. For most queries that does not matter, but it can affect retrieval quality for follow-up questions where the topic is implicit from prior context rather than stated explicitly in the current message.
Scoping memory by conversation
Without scoping, all users would share the same memory, which would be disastrous. The chat endpoint now requires an X-Conversation-Id header:
The caller is responsible for supplying and maintaining the conversation ID. The application does not generate or track session identifiers — that is intentional. For this demo, any string works. In production you would tie the conversation ID to an authenticated user session, but that is out of scope here.
The conversation ID is passed into the advisor chain at call time:
Spring AI reads that parameter, loads the matching rows from SPRING_AI_CHAT_MEMORY, prepends them to the prompt, and writes the new exchange back to the table when the call completes. The scoping is entirely key-based. Two requests with different conversation IDs read and write completely separate sets of rows. There is no shared state between them.
Trying it
Start the application and send two messages with the same conversation ID:
curl-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"My name is Maya."}'
curl-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-1"
-d'{"message":"What'''s my name?"}'
The second request should come back with “Maya”. Now try the same question with a different conversation ID:
curl-X POST http://localhost:8080/api/v1/agent/chat
-H"Content-Type: application/json"
-H"X-Conversation-Id: demo-2"
-d'{"message":"What'''s my name?"}'
The assistant should not know. The rows for demo-1 are invisible to a request arriving with demo-2. Memory does not leak between conversations.
Inspecting what Oracle is storing
There is a debug endpoint that reads directly from ChatMemory:
{"role":"assistant","text":"Nice to meet you, Maya! How can I help you today?"}
]
You can also go directly to the table:
SELECT*FROM SPRING_AI_CHAT_MEMORY;
These are ordinary rows. Conversation ID, role, content, timestamp. There is nothing opaque about the storage format. This also means the memory is durable — restart the application and the conversation history is still there, because it is in Oracle and not in process memory.
The model did not become smarter between episodes. The application stopped throwing away state.
Oracle is now storing three kinds of data
After Episode 1, Oracle was already handling two things: relational order data in CUSTOMER_ORDER, and vectorized policy knowledge in the Spring AI Oracle Vector Store table.
Episode 2 adds a third: conversational state in SPRING_AI_CHAT_MEMORY.
All three live in the same database. There is no separate vector store running alongside, no in-memory session cache to manage, no additional infrastructure to operate. The application connects to one Oracle instance and that instance holds everything the assistant needs — business data, knowledge, and conversation history.
That consolidation is not just operationally convenient. It also opens up possibilities that would be harder to achieve across separate systems. If you later wanted to run a query that joined conversation history with relational order data — for example, to find conversations where a customer mentioned an order that was then returned — all the data is in the same place. You do not have to reconcile records across multiple stores.
What is next
The assistant can now retrieve knowledge and remember conversations. But it still cannot act on any of the backend data. If a customer asks about the status of order ORD-1002, the assistant can only explain what the return policy says. It cannot look up the actual order.
Episode 3 changes that. Spring AI tool calling lets the assistant call narrow backend methods — order lookup, return initiation, support ticket creation — with the backend owning all the validation logic. The model handles the conversation. The backend handles the rules.
]]>https://redstack.dev/2026/05/15/add-persistent-chat-memory-to-your-spring-ai-chatbot-with-oracle-part-2-of-4/feed/04392What Is a Graph in Oracle AI Database 26ai?
https://redstack.dev/2026/05/13/what-is-a-graph-in-oracle-ai-database-26ai/
https://redstack.dev/2026/05/13/what-is-a-graph-in-oracle-ai-database-26ai/#commentsWed, 13 May 2026 13:31:07 +0000https://redstack.dev/?p=4365Continue reading →]]>If you have ever asked, “How is this thing connected to that thing?”, you have already asked a graph question.
A customer sends money to an account. That account sends money to two other accounts. One of those accounts sends money back to the original customer. In ordinary SQL, you can query each transfer. But when the real question is about chains, loops, hubs, and hidden intermediaries, the shape of the question becomes graph-shaped.
Oracle AI Database 26ai makes that graph shape part of the database instead of a separate side project. You can model a property graph over existing relational tables, query it with SQL graph syntax, join the results back to relational data, and then move into Graph Studio or PGX when you need visualization or heavier analytics.
Did you know that graphs were added to the SQL standard? Read about it here.
This series starts from zero. You do not need graph theory. You do not need a separate graph database. You need a basic comfort with SQL and a practical problem where relationships matter.
There are two ways you can try the runnable examples in this series. The first path is to use FreeSQL and this will work just fine for most of the examples: creating the tables, creating the graph, and querying patterns with GRAPH_TABLE. The second path is your own Autonomous Database Serverless instance on OCI for the full analytics chapter, because the DBMS_OGA algorithm examples require packages that are not available in the FreeSQL environment.
By the end of this article, you should be able to explain five ideas well enough to understand the graph DDL in the next article: vertex, edge, label, property, and directed relationship. You should also understand why Oracle’s 26ai graph approach is accessible from ordinary SQL instead of starting in a separate graph-only tool.
That is the only conceptual load for now. We will save weighted paths, algorithms, PGX, and natural-language querying for later articles, when those ideas have a working graph underneath them.
The Graph Mental Model
A graph has two main parts: vertices and edges.
A vertex is a thing. In a banking example, a vertex might be an account. In a social network, it might be a person. In a supply chain, it might be a warehouse, supplier, shipment, or part.
An edge is a relationship between things. In the banking example, a transfer from account 101 to account 102 is an edge. The edge has direction because money moved from one account to another.
Both vertices and edges can have properties. An account vertex can have an account id, customer id, account name, and balance. A transfer edge can have an amount, timestamp, channel, and note.
Labels give those things names in the graph model. In this series, account vertices use the label account, and transfer edges use the label transfer. Labels make graph patterns readable because you can ask for accounts connected by transfers instead of thinking only in table and column names.
That gives us a simple model:
account is a vertex;
transfer is an edge;
transfer direction goes from source account to destination account;
transfer amount and timestamp are edge properties;
customer id and balance are vertex properties.
The point is not to replace tables. The point is to describe relationships over data you already have.
That distinction helps avoid a common beginner mistake. You are not deciding whether the account data is “relational” or “graph.” It is relational data that also has a graph interpretation. Oracle lets you keep both views of the same facts.
Why Graph Questions Feel Different
Relational databases are excellent at storing and querying structured facts. A transfer table can tell you that account 101 sent 500 dollars to account 102. A customer table can tell you that account 102 belongs to a medium-risk customer.
Graph questions start when the relationship pattern matters.
For example:
Which accounts receive money from many different sources?
Which accounts sit in the middle of two-hop transfer chains?
Which accounts participate in round-trip transfer cycles?
Which high-risk customers are connected to suspicious paths?
You can answer some of these with ordinary joins, especially when the path length is fixed and short. But the queries become harder to read as soon as you want to ask about paths, cycles, or repeated relationship patterns.
That is where GRAPH_TABLE becomes useful. It lets you describe a graph pattern and return the matches as rows. Once the graph match is back in row form, you can use normal SQL again: filter it, aggregate it, join it, and sort it.
What Changed In 26ai
In Oracle AI Database 26ai, SQL property graphs are native database objects. You create them with CREATE PROPERTY GRAPH, and you query them with SQL graph syntax such as GRAPH_TABLE.
The important beginner idea is this: a SQL property graph is metadata over database objects. You do not have to copy all of your rows into a separate graph store just to start asking graph questions. The graph definition says which tables provide vertices, which tables provide edges, how the keys connect, which labels to use, and which properties to expose.
For the bank example in this series, the relational data is still stored in ordinary tables:
customers
bank_accounts
bank_transfers
The graph object simply gives those tables graph meaning:
bank_accounts becomes account vertices;
bank_transfers becomes transfer edges;
src_account_id and dst_account_id define edge direction.
That is why graph in 26ai is a good fit for developers and DBAs who already work with Oracle Database. You can start with SQL, keep the data where it is, and add graph-shaped queries where they help.
Why Not RDF?
Oracle supports RDF graphs too, but this series is about property graphs. RDF is the better fit when the work centers on formal semantics, ontologies, inferencing, and standards-based knowledge representation. Property graphs are the better starting point here because the question is operational and concrete: how are these accounts connected, and what suspicious patterns do those connections form?
The Bank Fraud Story We Will Use
The rest of this series uses a small bank-fraud style example. It is intentionally tiny so you can understand every row.
The demo has customers, accounts, and transfers. Some transfers form a simple cycle. Other transfers create a fan-in pattern where several accounts send money to the same destination. Another chain places a high-risk customer in the middle.
That gives us enough data to teach useful graph ideas without hiding the lesson inside a huge dataset.
Here is the shape of the data we will use throughout this series:
customers bank_accounts bank_transfers
---------- ------------- --------------
customer_id -> customer_id transfer_id
risk_tier account_id -> src_account_id
account_name -> dst_account_id
balance amount
transfer_ts
channel
The SQL property graph gives those tables this connected shape:
(account)-[transfer]->(account)
That one pattern, account connected to account by transfer, is enough to teach all four articles’ worth of graph concepts: paths, cycles, hubs, chains, ranking, connected groups, and hybrid SQL joins.
Where This Series Is Going
The next article builds the graph. We will create the tables, load seed data, define BANK_GRAPH, and inspect the graph metadata.
After that, we will query fraud patterns with GRAPH_TABLE. Then, in ADB-S, we will add in-database algorithms with DBMS_OGA and use Graph Studio to visualize the same graph.
The goal is not to memorize every graph feature. The goal is to build a practical mental model:
start with relational data;
define a SQL property graph;
query graph patterns with SQL;
join graph results to ordinary data;
move into Graph Studio or PGX when you need visualization or deeper analytics.
That is the zero-to-hero path.
Try The Demo
The fastest way to make the ideas concrete is to run the tiny bank demo yourself. The first runnable step creates three ordinary relational tables:
customers
bank_accounts
bank_transfers
Those tables hold the facts. The next step creates BANK_GRAPH, a SQL property graph over the account and transfer rows. Nothing is copied into a separate graph store; the graph definition gives the existing rows a connected shape.
Note: this will ask you to login with your oracle.com account since it writes to the database, not just reads. It’s totally free. I recommend you read through the SQL first to understand what it does, then click on the “Run Script” button to execute it, and then scroll through the output to see what happened. Feel free to play around with it and change it however you like!
In the next article, you’ll load the seed data and create the graph. If you prefer to use your own Autonomous Database Serverless instance, copy the same SQL into your SQL Worksheet and run it there. Either way, keep the data small at first. The goal is to see the graph model clearly before adding larger datasets, algorithms, or visualization.
Once BANK_GRAPH exists, the later examples will use the same graph to find inbound hubs, transfer chains, cycles, PageRank scores, connected groups, and weighted paths.
]]>https://redstack.dev/2026/05/13/what-is-a-graph-in-oracle-ai-database-26ai/feed/14365Build a stateless RAG chatbot with Spring AI and Oracle (part 1 of 4)
https://redstack.dev/2026/05/12/4355/
https://redstack.dev/2026/05/12/4355/#commentsTue, 12 May 2026 13:09:35 +0000https://redstack.dev/?p=4355Continue reading →]]>Hi everyone!
I just posted the first video in this series about building AI assistance with memory and agency. In this video, we built a simple customer support assistant using Spring Boot, Spring AI, and Oracle Database. It answers policy questions, but the key idea is that those answers are grounded in data stored in Oracle rather than coming from the model itself.
In this post I want to walk through how the application is actually put together, focusing on the pieces that make that retrieval flow work.
If you clone the repo and open it up, it looks like a normal Spring Boot application. The difference is how Oracle is used underneath, and how that gets wired into the chat flow.
A good place to start is with how the database is brought up locally.
In compose.yaml, the application relies on Spring Boot’s Docker Compose support to start Oracle automatically:
services:
oracle:
image: gvenzl/oracle-free:23.26.1-slim
ports:
- "1521"
environment:
ORACLE_PASSWORD: oracle
APP_USER: shopassist
APP_USER_PASSWORD: shopassist
There’s nothing unusual here, but it’s worth noting that this is just a standard Oracle instance. There’s no separate “vector database” running anywhere. The same database is going to store both relational data and vector embeddings.
Once that container is running, the next piece is how the application connects to it.
In application.yml, you can see both the datasource configuration and the vector store configuration side by side:
This is where Oracle AI Vector Search becomes visible in the application.
The initialize-schema flag tells Spring AI to create the underlying tables needed to store embeddings. Once that happens, the database is no longer just storing rows – it’s storing vectors that can be searched using similarity.
The distance-type: COSINE setting controls how similarity is calculated, which is what allows us to retrieve “related” documents even when the wording is different.
With that in place, the next question is how data actually gets into the vector store.
That happens in DataSeeder.java, and this is one of the more important pieces of the application because it defines what the system actually knows.
If you look at the seeder, you’ll see the policy documents being added like this:
vectorStore.add(List.of(
newDocument("""
POL-RETURN-01:
Returns are accepted within 30 days of purchase with a valid receipt.
Refunds are issued to the original payment method.
"""),
newDocument("""
POL-DAMAGE-01:
Damaged items must be reported within 48 hours of delivery.
Customers may request a replacement or refund.
"""),
newDocument("""
POL-SHIPPING-01:
Shipping delays may occur due to weather or carrier issues.
Customers will be notified of significant delays.
"""),
newDocument("""
POL-REFUND-01:
Refunds are typically processed within 5-7 business days after approval.
Processing times may vary by payment provider.
""")
));
Each of these documents is embedded and stored in Oracle. That’s what allows us to later take a user’s question, convert it into a vector, and find the most similar documents using Oracle AI Vector Search.
The same class also seeds some relational order data, which we expose through /api/v1/orders. That isn’t used by the chatbot yet, but it becomes important later when we start combining retrieval with structured queries.
Once the data is in place, the next piece is how a request flows through the system.
If you open AgentController.java, the endpoint itself is intentionally simple:
When chatClient.prompt(...).call() is invoked, this advisor intercepts the request, runs a similarity search against Oracle, and retrieves the top three matching documents.
Those documents are then injected into the prompt that gets sent to the model.
So when a user asks something like “How long do refunds take?”, the system first retrieves the refund policy from Oracle and then asks the model to generate an answer based on that context.
One small addition that makes this much easier to see is the debug endpoint. Instead of going through the full chat flow, this endpoint lets you query the vector store directly and inspect what Oracle returns.
There’s nothing complicated here, but it’s doing something important. Instead of calling the model, it calls vectorStore.similaritySearch(...) directly using the same search configuration.
So when you hit:
GET /api/v1/debug/policies/search?q=refund
you’re seeing exactly what Oracle returns for that query. The same embeddings, the same cosine similarity, the same top-K logic—just without the LLM step.
This makes it much easier to reason about the system. If the wrong documents show up here, the model never had a chance to produce the right answer. If the right documents show up here but the answer is still off, then you know to look at prompt construction instead.
At this point, the application is doing something useful, but it’s also very clearly limited because it is completely stateless.
If you try something like:
My name is Maya.
and then follow it with:
What’s my name?
the system won’t be able to answer. Each request is handled independently, and the only context available is the current message plus whatever documents were retrieved from Oracle.
There is no conversation history, and nothing is stored between requests.
This is the key distinction to understand at this stage. Oracle AI Vector Search gives us a way to retrieve relevant knowledge from stored data, but it does not give us memory. The system can answer policy questions because those policies are embedded and searchable, but it cannot remember something you just told it.
That limitation is intentional, because it sets up the next step. In the next episode we’ll introduce persistent chat memory, add conversation identifiers, and start maintaining context across requests.
For now, this version gives us a clean, grounded foundation: a Spring Boot service where Oracle stores embeddings, performs similarity search, and provides the context that the model uses to generate responses. Everything else we add will build on top of that.
]]>https://redstack.dev/2026/05/12/4355/feed/14355Exploring Oracle’s new AI Agent Memory Python Library with OpenAI
https://redstack.dev/2026/05/06/exploring-oracles-new-ai-agent-memory-python-library-with-openai/
https://redstack.dev/2026/05/06/exploring-oracles-new-ai-agent-memory-python-library-with-openai/#respondWed, 06 May 2026 18:59:27 +0000https://redstack.dev/?p=4331Continue reading →]]>Hi everyone!
In this post, I want to show you a small but useful demo application that uses Oracle AI Agent Memory from Python. The complete code for this example is in the agent-memory repository. You can learn more about Oracle AI Agent Memory on the Oracle website.
The demo is a customer support assistant. That is a nice shape for an agent memory example because it gives us all the things agents usually need to remember: who the user is, what happened before, which device or account is involved, what the current case state is, and whether this new problem sounds like an earlier one.
The important point is that oracleagentmemory is the memory layer. It is not tied to one agent framework. You can use it with different frameworks and SDKs. This particular sample uses the OpenAI SDK for the agent-style tool-calling loop, and it uses Oracle AI Agent Memory as the durable memory backend.
In other words, OpenAI drives the agent turn. Oracle stores and retrieves the memory.
Let’s walk through it.
What we are building
The sample application does five things:
starts a local Oracle Database Free container
creates the Oracle AI Agent Memory managed schema
creates a small companion schema for customer, device, case, policy, JSON state, and graph data
runs a scripted support conversation with memory-aware tool calls
prints a database inspection report so we can see where the memory went
The scenario centers on Alex, a support user with a River House account and a Model X router. Alex had a prior Wi-Fi dropout issue. Later, Alex comes back and says video calls are unstable again. The agent needs to figure out whether that sounds related, what facts it already knows, what relationships matter, and what to do next.
That gives us a realistic demo without needing a real ticketing system, CRM, or router telemetry feed.
Before you begin
You need Python, Docker, uv, and an OpenAI API key.
The quickstart from the repository is:
cp .env.example .env
# Edit .env and set OPENAI_API_KEY.
uv sync
uv run agent-memory-demo run
The demo uses gvenzl/oracle-free:23.26.1-slim-faststart by default. That is helpful for a local demo because the database starts faster than a normal first-start image.
The repository also sets these defaults:
OPENAI_MODEL=gpt-5-mini
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
OPENAI_MEMORY_LLM_MODEL=gpt-5-mini
ORACLE_MEMORY_TABLE_PREFIX=OAM_DEMO_
ORACLE_APP_TABLE_PREFIX=OAM_DEMO_APP_
The two prefixes matter. The OAM_DEMO_ tables are managed by Oracle AI Agent Memory. The OAM_DEMO_APP_ tables are the companion business tables created by this sample application.
That separation makes the demo easier to understand. We can see what the library owns, and we can also see the normal application data that the agent works with.
Why agent memory is not just one thing
When people first talk about agent memory, they often mean one thing: chat history. That is useful, but it is not enough.
A useful agent may need several kinds of memory:
Memory kind
What it means in this demo
Oracle storage used
When to use it
Working or thread memory
The current and previous support messages
Relational rows in managed Agent Memory tables
Use this when the agent needs conversation continuity.
Durable fact memory
Preferences, facts, and case summaries that should survive the current conversation
Managed Agent Memory records, plus vector chunks for retrieval
Use this when the agent should remember something later.
Profile memory
User and agent profiles
Relational rows
Use this for stable actor information such as user preferences or agent identity.
State memory
The mutable status of a support case
JSON in the app-owned case table
Use this when the shape of the state may evolve over time.
Relationship memory
User to account to device to case to policy paths
SQL Property Graph over relational vertex and edge tables
Use this when the important question is about connected things.
Similarity memory
Prior cases or memories that are semantically close to the current issue
Oracle VECTOR columns in record chunks
Use this when the same thing may be described in different words.
That is the main architectural idea in the demo. Different memory types have different access patterns, so they should not all be forced into the same shape.
Relational data is great when identifiers, constraints, ownership, and joins matter. JSON is great when the shape of state changes as the case moves forward. Graph is great when paths and relationships are the point. Vector data is great when similarity matters more than exact matching.
The nice thing here is that all of those can live in Oracle Database. The agent does not need a separate relational database, graph database, document database, and vector database just to remember one support case.
The repository structure
The application code lives under src/agent_memory_demo.
The key files are:
File
What to look for
cli.py
The Typer commands: run, interactive, inspect-db, verify-memory, and reset-db.
container.py
The local Oracle container lifecycle.
config.py
Environment variable loading and defaults.
memory.py
Creation of the OracleAgentMemory client.
agent.py
The OpenAI tool-calling loop and tool schemas.
tools.py
Tool handlers for memory search, saving memory, context, JSON state, graph paths, and inspection.
schema.py
The app-owned relational, JSON, and graph schema.
seed.py
Deterministic demo data.
inspect.py
Database inspection output, including vector storage evidence.
The sample is intentionally small, but it is not a toy in the sense of hiding the database. It shows the database because that is the point of the demo.
Creating the memory client
The memory setup happens in memory.py.
The demo creates an OracleAgentMemory client with:
an Oracle database connection
an embedding model
an LLM model for memory extraction and summaries
a schema policy
a table name prefix
The schema policy is important. Normal startup uses SchemaPolicy.CREATE_IF_NECESSARY, so the managed Agent Memory schema is created if it is not already there. The reset-db command uses the recreate policy for an explicit destructive reset.
That gives the sample a clean local developer workflow. You can run it, inspect it, reset it, and run it again without needing a manually installed database.
The agent loop
The OpenAI side of the sample lives in agent.py.
The agent loop sends a user message, instructions, and a list of function tools to the OpenAI SDK. When the model returns tool calls, the application executes the local Python handler, sends the tool output back, and repeats until the model produces final text.
The useful part is that the tools map to different memory operations:
Tool
What it demonstrates
search_memory
Scoped Agent Memory search.
save_memory
Explicit durable memory writes.
get_context
A thread context card.
update_case_state
JSON state updates in the support case table.
find_related_case
Vector-backed semantic retrieval of similar case memories.
explain_relationships
SQL Property Graph traversal.
inspect_memory_tables
Database evidence for the demo.
This is a useful pattern for agent applications. The model does not get direct database access. It gets tools. Each tool has a focused job, a scoped input shape, and a handler that decides what database operation is safe and appropriate.
The companion schema
The sample creates app-owned tables for customers, devices, support cases, policies, graph vertices, and graph edges.
This is separate from the managed Agent Memory schema. That is a good design choice because most real applications already have business data. Agent memory should not replace that data. It should work with it.
The support case table uses JSON for mutable state. A case might start as open, then get a next action, then become escalation-ready, then later get a resolution. That kind of state is structured, but it can change over time. JSON is a good fit.
The graph tables show relationships. Alex owns an account. The account has a router. The router has a case. The case uses a policy. That is exactly the kind of question where graph traversal is easier to read than a pile of joins.
The managed Agent Memory tables store threads, messages, memory records, actor profiles, and record chunks. The record chunks are where the vector-backed similarity story becomes visible.
Run the scripted demo
Start with the main command:
uv run agent-memory-demo run
The run command starts the Oracle container, creates demo schema objects, seeds deterministic data, runs a scripted support conversation, shows memory tool usage, prints the final assistant answer, and includes a database inspection report before the container is removed.
There are a few things to watch for in the output.
First, the demo creates both user and agent profiles. That shows profile memory, not just chat memory.
Second, it creates an initial thread and stores messages. That gives the agent working memory and a durable record of the conversation.
Third, it saves explicit memory. The demo records facts like Alex’s router and contact preferences.
Fourth, it creates a second thread for a follow-up problem and shows the difference between broad thread matching and exact thread matching. That is a subtle but important behavior. Sometimes you want memories from the same user and agent across threads. Sometimes you only want the current thread.
Fifth, it shows scope isolation. A search scoped to another user should not see Alex’s memories.
Finally, the OpenAI tool calls are printed with their JSON arguments and compact results. That makes the agent loop much easier to reason about because you can see what the model asked for and what the database returned.
The output is color-coded:
green for user messages
magenta for assistant messages
yellow for OpenAI tool calls and arguments
blue for Oracle database, graph, and tool-result evidence
cyan for progress and memory setup or search visibility
That may sound like a small thing, but it makes the demo much easier to follow while it runs.
Run the interactive demo
The repository also includes an interactive mode:
uv run agent-memory-demo interactive
This starts a memory-enabled assistant using the same command-scoped Oracle container lifecycle. It seeds the same companion data and stores your turns in a scoped Agent Memory thread.
One practical detail: the container is command-scoped. It exists while the command is running and is removed when the command exits. So if you want to inspect the database manually, leave the interactive session open.
The README says to wait for output like this:
Started Oracle demo database at localhost:32838/FREEPDB1
Seeded companion relational, JSON, graph, and policy data.
Interactive Oracle AI Agent Memory demo. Type 'quit' to exit.
you>:
Then, before inspecting the database, ask a prompt that creates some memory activity:
For user_id=user_alex and agent_id=support_agent, inspect memory tables and tell me what you can see in one sentence.
Now keep that terminal open and inspect the database from another terminal.
Inspect the database
There is a command for a quick database evidence report:
uv run agent-memory-demo inspect-db
This starts a temporary Oracle container, seeds the deterministic companion data, prints table counts, JSON case state, and graph paths, and then tears the container down.
One thing to know: inspect-db does not create Agent Memory records. That means managed memory table counts are expected to be zero for that command. Use run or verify-memory when you want to populate and inspect memory and vector chunk tables.
For hands-on SQL inspection, keep the interactive session open and connect from a second terminal. Replace the port with the one printed by your run:
That is where the storage story becomes concrete. You should see the normal relational columns, the JSON columns in the app-owned tables, and, after running a memory-populating command, the vector-related storage in the managed record chunk table.
The graph edge indexes are also useful to inspect:
This is a good example of why JSON is useful here. The case state is still queryable from SQL, but the state document can evolve as the workflow evolves.
Finally, after running a memory-populating command, look at the managed Agent Memory tables:
SELECT*
FROM OAM_DEMO_MEMORY
FETCHFIRST5ROWSONLY;
SELECT*
FROM OAM_DEMO_RECORD_CHUNKS
FETCHFIRST5ROWSONLY;
This query shows the vector columns:
SELECT column_name, data_type
FROM user_tab_columns
WHERE table_name ='OAM_DEMO_RECORD_CHUNKS'
AND data_type ='VECTOR';
And this one shows vector indexes:
SELECT index_name, index_type
FROM user_indexes
WHERE table_name ='OAM_DEMO_RECORD_CHUNKS'
ORDERBY index_name;
That is the part I like most in this demo. We are not just saying that memory is persistent. We can actually look at the tables and see how different kinds of memory are represented.
Verify graph and vector behavior
The verify-memory command is a nice acceptance check:
uv run agent-memory-demo verify-memory
It seeds explicit Agent Memory records, runs graph traversal, runs vector-backed similarity search, and prints metadata evidence for the managed OAM_DEMO_RECORD_CHUNKS table.
The expected similar prior router case is case_wifi_dropout_001.
That matters because the follow-up issue does not have to use the exact same words as the earlier issue. Vector search can connect “video calls freeze” with a prior router dropout case because the meaning is similar.
This is the right place to use vectors. You are not asking for the one row with a known primary key. You are asking, “Have we seen something like this before?”
When to use each Oracle data type
Here is the practical version.
Use relational tables for the things you must identify and constrain: users, accounts, devices, cases, policies, threads, messages, and profile rows. Relational data gives you keys, constraints, indexes, joins, and ownership boundaries. That is still the backbone of most useful applications.
Use JSON for flexible state. In this sample, support case state lives in JSON because the state can change as the workflow changes. The update_case_state tool uses JSON_MERGEPATCH to update the state document without replacing the whole application model.
Use graph for connected context. If the agent needs to understand that Alex owns an account, the account has a router, the router has a case, and the case uses a policy, graph traversal makes that relationship path explicit. In this sample, explain_relationships uses a SQL Property Graph query to return user-account-device-case-policy paths.
Use vectors for similarity. If the user describes the same issue with different words, exact search is not enough. Vector search lets the agent find semantically similar memories and prior cases. In this sample, case summary memories are embedded into record chunks, and the find_related_case tool searches those chunks through Oracle Agent Memory.
The real value is not that any one of these exists. The value is that the sample can use all of them together.
Reset the demo
If you want to exercise the destructive reset path, the repository includes this command:
uv run agent-memory-demo reset-db
That resets the app-owned companion schema and recreates the managed Agent Memory schema. It is a demo command, not something to point at a production schema.
What this sample teaches
There are a few patterns here that are worth carrying into real applications.
First, keep the memory backend separate from the agent framework. This demo uses the OpenAI SDK tool loop, but the memory concepts are not OpenAI-specific. The agent needs tools. The memory system needs scoped APIs. Those two things meet at a clean boundary.
Second, scope everything. The demo uses user, agent, and thread boundaries. It also shows that another user should not see Alex’s memories. That is not just a demo flourish. It is table stakes for real multi-user agents.
Third, use the right data shape for the job. Chat messages, durable memories, JSON state, graph relationships, and vector chunks are not the same thing. Treating them differently makes the system easier to reason about.
Fourth, inspect the database. Agent demos can feel magical if all you see is a final answer. This demo is better because it shows the rows, JSON state, graph paths, and vector storage evidence. That makes the behavior testable and explainable.
Wrap up
We built and inspected a memory-enabled support assistant using oracleagentmemory, the OpenAI SDK, and a local Oracle Database container.
The sample shows working memory through threads and messages, durable memory through explicit memories and extracted facts, profile memory for users and agents, JSON state for support cases, relationship memory through SQL Property Graph, and similarity memory through vector-backed record chunks.
The important idea is simple: agents need more than chat history. They need memory that is durable, scoped, queryable, and connected to the data the application already trusts.
This demo gives you a compact way to see that pattern end to end.
]]>https://redstack.dev/2026/05/06/exploring-oracles-new-ai-agent-memory-python-library-with-openai/feed/04331Building an Authorization Server with Spring Boot 4 and Oracle Database
https://redstack.dev/2026/05/04/building-an-authorization-server-with-spring-boot-4-and-oracle-database/
https://redstack.dev/2026/05/04/building-an-authorization-server-with-spring-boot-4-and-oracle-database/#respondMon, 04 May 2026 13:59:00 +0000https://redstack.dev/?p=4317Continue reading →]]>Hi again everyone!
In this post I want to show you how to build a small authorization server using Spring Boot, Spring Security, Spring Authorization Server, and Oracle Database. The idea is simple: we want an application that can expose OAuth2/OIDC authorization-server endpoints, authenticate users whose details are stored in Oracle Database, and provide a small REST API for managing those users.
The complete code for this example is in theazn-server repository. In this article we will build it from scratch and look at the important pieces along the way.
One important note before we start: this version of the example is on the Spring Boot 4.x code line. The repository currently uses Spring Boot 4.0.6, Java 21, Spring Framework 7.0.7, Spring Security 7.0.5, Spring Cloud 2025.1.1, Liquibase 5.0.2 from the Spring Boot BOM, and the Oracle Spring Boot starters.
If you have seen the Spring Boot 3.x version of this sample, the application shape is intentionally the same. The Boot 4 version updates the dependency line and uses the new modular starter names and package names introduced across Spring Boot 4, Spring Framework 7, and Spring Security 7.
What we are building
The application has three main responsibilities:
Expose OAuth2 and OpenID Connect endpoints using Spring Authorization Server.
Store application users in Oracle Database.
Provide a secured user-management API backed by Spring Security method security.
Spring Security gives us a lot here. It gives us the authentication framework, password encoding, UserDetailsService integration, filter chains, method-level authorization, role hierarchy support, and the authorization-server protocol endpoints. Oracle Database gives us a durable user repository, schema ownership, constraints, identity columns, auditing triggers, and a real database engine for integration tests.
This is the application shape:
Spring Boot starts the service.
Liquibase creates or updates the Oracle schema user.
Liquibase creates the USERS table and audit trigger.
JPA maps the USERS table into a User entity.
Spring Security loads users from that JPA repository.
Spring Authorization Server exposes the OAuth2/OIDC endpoints.
The REST API lets administrators manage users.
Let’s walk through the build.
Create the Spring Boot project
We start with a normal Spring Boot application. The important thing is to include the dependencies for web endpoints, Spring Authorization Server, actuator, JPA, Liquibase, Oracle UCP, Oracle wallet support, and the test stack.
The parent and version properties select the Spring Boot 4 and Spring Cloud lines:
First, spring-boot-starter-security-oauth2-authorization-server brings in the Spring Authorization Server support that provides the OAuth2/OIDC protocol endpoints. That means we do not have to hand-code token endpoints, metadata endpoints, JWK endpoints, or the protocol filter chain.
Spring Boot 4 is more modular than the 3.x line. For this servlet application, the web starter is now spring-boot-starter-webmvc, the test slice starter is spring-boot-starter-webmvc-test, and the authorization-server starter lives under the security naming scheme. The Testcontainers 2 artifacts also use the testcontainers-* artifact names shown above. Letting the Spring Boot parent manage the versions keeps Spring Framework, Spring Security, Liquibase, Jackson, Hibernate, and Testcontainers aligned.
Second, the Oracle UCP starter gives us Oracle Universal Connection Pool integration through Spring Boot configuration. That is useful for real services because the database connection pool is not an afterthought – it is part of the application runtime.
Third, Liquibase owns the schema. Hibernate validates the schema, but Liquibase creates it. That is usually the right split for applications where the database is important enough to be managed deliberately.
Configure Oracle Database and Liquibase
The application uses two database identities:
A Liquibase/admin identity that can create and update the application schema.
A runtime schema user named USER_REPO that the application uses for normal database access.
Here is the application configuration:
server:
port: 8080
spring:
application:
name: @project.artifactId@
cloud:
# Discovery is opt-in so local runs and tests do not attempt to register.
discovery:
enabled: ${EUREKA_CLIENT_ENABLED:false}
threads:
virtual:
enabled: true
datasource:
# Runtime connections authenticate directly as the application schema user.
I like this arrangement because the runtime user is not the same as the schema-management user. Liquibase gets the elevated account it needs to create and manage USER_REPO, and the running application connects as USER_REPO. That is a clean security boundary.
That gives us Oracle-aware connection pooling with very little Spring code. We get the operational benefit of a pool that is meant for Oracle Database, while still configuring it in the usual Spring Boot way.
Create the schema with Liquibase
The changelog controller is small:
---
databaseChangeLog:
-include:
file: classpath:db/changelog/dbuser.sql
-include:
file: classpath:db/changelog/table.sql
-include:
file: classpath:db/changelog/trigger.sql
The first changelog creates and maintains the USER_REPO database user:
This is a nice example of letting the database enforce something that belongs in the database. Every update gets audit fields set consistently, whether the update came from this Spring application or from another controlled path later.
Map the Oracle table to a JPA entity
Now we need a JPA entity for the USER_REPO.USERS table.
// Copyright (c) 2023, 2026, Oracle and/or its affiliates.
There are two small but important security choices in this class.
First, password and otp are write-only for JSON serialization. That means the API can accept these values in request bodies, but it will not serialize them back into responses.
Second, Lombok’s @ToString excludes password and otp. That helps prevent secrets from being accidentally written into logs.
The repository is exactly what we want from Spring Data JPA: small, declarative, and focused on the queries the service needs.
// Copyright (c) 2022, 2023, Oracle and/or its affiliates.
This is one of the places where Spring Data JPA shines. The method names communicate intent, Spring implements the queries, and the application code stays readable.
Adapt the database user to Spring Security
Spring Security authenticates with UserDetails. Our database user is a domain object, so we wrap it in a SecurityUser.
// Copyright (c) 2022, 2026, Oracle and/or its affiliates.
This is the bridge between Oracle Database and Spring Security. Once this service exists, Spring Security can authenticate users stored in USER_REPO.USERS.
Configure Spring Security and Spring Authorization Server
The security configuration is the heart of the application. It does several things:
Creates a role hierarchy.
Enables method security.
Creates a dedicated authorization-server filter chain.
Creates a separate actuator filter chain.
Creates a stateless API filter chain.
Provides password encoding.
Provides development/test signing keys.
Optionally creates a local OAuth client.
Here is the role hierarchy:
public static final String ROLE_HIERARCHY = "ROLE_ADMIN > ROLE_USERn"
+ "ROLE_ADMIN > ROLE_CONFIG_EDITORn"
+ "ROLE_CONFIG_EDITOR > ROLE_USER";
/**
* Configure a role hierarchy such that ADMIN "includes"/implies USER.
*
* @return the hierarchy.
*/
@Bean
public RoleHierarchy roleHierarchy() {
return RoleHierarchyImpl.fromHierarchy(ROLE_HIERARCHY);
}
/**
* Configure method security to use the role hierarchy.
*
* @param roleHierarchy injected by Spring.
* @return The MethodSecurityExpressionHandler.
*/
@Bean
public MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setRoleHierarchy(roleHierarchy);
return expressionHandler;
}
Role hierarchy is one of those Spring Security features that is easy to miss but very useful. If an administrator should also be treated as a user, we do not have to duplicate every role check everywhere. We can teach Spring Security that ROLE_ADMIN includes ROLE_USER.
The authorization server gets its own filter chain:
/**
* Authorization Server endpoints use their own filter chain so OAuth protocol
* handling does not inherit API-specific stateless settings.
*
* @param http HttpSecurity injected by Spring.
* @return the SecurityFilterChain.
* @throws Exception if unable to create the chain.
*/
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
throws Exception {
log.debug("In authorizationServerSecurityFilterChain");
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer();
http
.securityMatcher(authorizationServerConfigurer.getEndpointsMatcher())
.with(authorizationServerConfigurer, authorizationServer ->
authorizationServer.oidc(Customizer.withDefaults()))
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/.well-known/**", "/oauth2/jwks").permitAll()
.anyRequest().authenticated())
.csrf((csrf) -> csrf.ignoringRequestMatchers(authorizationServerConfigurer.getEndpointsMatcher()))
.exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/login"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)));
return http.build();
}
This is where Spring Authorization Server does a lot of heavy lifting. The endpoints matcher identifies the protocol endpoints, OIDC support is enabled, and the well-known metadata and JWK endpoints are allowed anonymously.
In the Spring Boot 4 version, the authorization-server configurer comes from the Spring Security 7 package org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization. The older static factory used by the Boot 3 version is gone, so the sample constructs the configurer directly and then applies it to HttpSecurity.
The user-management API has a different shape. It is stateless and uses HTTP Basic:
/**
* Create a SecurityFilterChain for the user-management API.
* @param http HttpSecurity injected by Spring.
* @param userDetailsService the JPA-backed user details service.
* @return the SecurityFilterChain.
* @throws Exception if unable to create the chain.
*/
@Bean
@Order(3)
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, UserDetailsService userDetailsService)
throws Exception {
log.debug("In apiSecurityFilterChain");
http
.securityMatcher("/user/api/**", "/error/**")
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/error/**").permitAll()
.requestMatchers("/user/api/v1/ping").permitAll()
.requestMatchers("/user/api/v1/forgot").permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.userDetailsService(userDetailsService);
// The user-management API is stateless and does not use browser sessions or cookies.
http.csrf(csrf -> csrf.disable());
return http.build();
}
The separation between the authorization-server chain and the API chain matters. The OAuth2/OIDC endpoints are protocol endpoints. The user API is a REST API. They have different security needs, so they get different chains.
The authentication provider uses our JPA-backed user details service and a BCrypt password encoder:
/**
* Create an Authentication Provider for our UserDetailsService.
* @param userDetailsService the JPA-backed user details service.
* @param passwordEncoder password encoder for stored password hashes.
* @return the AuthenticationProvider.
*/
@Bean
public DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider(userDetailsService);
auth.setPasswordEncoder(passwordEncoder);
return auth;
}
And the password encoder is:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Passwords in the API enter as clear text at the boundary, but they are stored as BCrypt hashes in Oracle Database. That is exactly the line we want: clear text only at the edge, hashes at rest.
For local development and tests, the application can create an opt-in registered client:
/**
* Create an opt-in local client for test and developer-only contexts.
*
* Production deployments should configure registered clients explicitly using
* Spring Boot's authorization-server client properties.
*
* @param passwordEncoder password encoder for the client secret.
* @param clientSecret configured client secret.
* @return a local RegisteredClientRepository.
*/
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "azn.authorization-server.default-client", name = "enabled",
havingValue = "true")
public RegisteredClientRepository localRegisteredClientRepository(PasswordEncoder passwordEncoder,
@Value("${azn.authorization-server.default-client.secret:}") String clientSecret) {
if (!StringUtils.hasText(clientSecret)) {
throw new IllegalStateException("azn.authorization-server.default-client.secret must be set when "
+ "azn.authorization-server.default-client.enabled=true");
}
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("azn-local-client")
.clientSecret(passwordEncoder.encode(clientSecret))
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/azn-local-client")
.scope(OidcScopes.OPENID)
.scope("user.read")
.clientSettings(ClientSettings.builder().requireProofKey(true).build())
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
Notice that this is opt-in. That is intentional. Local convenience is useful, but production registered clients should be configured deliberately.
The JWK source is also local by default:
/**
* Provide process-local signing keys for development and tests.
*
* Production deployments should replace this bean with persistent key material
* so tokens remain verifiable across restarts and rolling deploys.
*
* @return the JWK source.
*/
@Bean
@ConditionalOnMissingBean
public JWKSource<SecurityContext> jwkSource() {
log.warn("Using process-local generated RSA signing keys. Configure a persistent JWKSource bean for "
+ "production so issued tokens remain verifiable across restarts and rolling deploys.");
RSAKey rsaKey = generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
That is fine for development and tests. For production, you would provide persistent signing key material so tokens remain verifiable across restarts and rolling deployments.
Bootstrap the first users
An authorization server needs at least one user to get started. This application creates three bootstrap users on startup by default:
And the implementation creates missing users with BCrypt-encoded passwords:
public static void initUserStore(UserRepository users, PasswordEncoder encoder,
String adminPassword, String userPassword) {
log.debug("ENTER initUserStore");
String obaasAdminPwd = adminPassword;
String obaasUserPwd = userPassword;
String obaasConfigPwd = obaasUserPwd;
// Check for obaas-user, if not existent create the user
if (users.findByUsername(OBAAS_USER).isEmpty()) {
log.debug("Creating user obaas-user");
obaasUserPwd = bootstrapPassword("azn.bootstrap-users.user-password", obaasUserPwd);
users.saveAndFlush(new User(OBAAS_USER, encoder.encode(obaasUserPwd),
"ROLE_USER"));
}
// Check for obaas-admin, if not existent create the user
Optional<User> adminUser = users.findByUsername(OBAAS_ADMIN);
if (adminUser.isEmpty()) {
log.debug("Creating user obaas-admin");
obaasAdminPwd = bootstrapPassword("azn.bootstrap-users.admin-password", obaasAdminPwd);
users.saveAndFlush(new User(OBAAS_ADMIN, encoder.encode(obaasAdminPwd),
"ROLE_ADMIN,ROLE_CONFIG_EDITOR,ROLE_USER"));
}
// Check for obaas-config, if not existent create the user with the same pwd as
// obaas-user
if (users.findByUsernameIgnoreCase(OBAAS_CONFIG).isEmpty()) {
log.debug("Creating user obaas-config");
obaasConfigPwd = bootstrapPassword("azn.bootstrap-users.user-password", obaasConfigPwd);
users.saveAndFlush(new User(OBAAS_CONFIG, encoder.encode(obaasConfigPwd),
"ROLE_CONFIG_EDITOR,ROLE_USER"));
}
}
The bootstrap passwords come from external configuration. If bootstrap users are enabled and the password properties are missing, startup fails:
private static String bootstrapPassword(String propertyName, String configuredPassword) {
if (StringUtils.isNotBlank(configuredPassword)) {
return configuredPassword;
}
throw new IllegalStateException(propertyName + " must be set when azn.bootstrap-users.enabled=true");
}
That is much better than quietly creating default passwords.
@PreAuthorize(isAdminUser)
@PostMapping("/createUser")
public ResponseEntity<?> createUser(@RequestBody User user) {
// If user exists return HTTP Status 409.
Optional<User> checkUser = userRepository.findByUsernameIgnoreCase(user.getUsername());
if (checkUser.isPresent()) {
log.debug("User exists");
return new ResponseEntity<>("User already exists", HttpStatus.CONFLICT);
}
if (!isValidPassword(user.getPassword())) {
return new ResponseEntity<>("Password does not meet complexity requirements",
HttpStatus.UNPROCESSABLE_ENTITY);
}
if (StringUtils.isNotEmpty(user.getEmail())) {
Optional<User> userAlreadyAssociatedWithEMail = userRepository.findByEmailIgnoreCase(user.getEmail());
if (userAlreadyAssociatedWithEMail.isPresent()) {
log.debug("User exists");
return new ResponseEntity<>("Another user exists with same email", HttpStatus.CONFLICT);
}
}
// Validate roles in RequestBody
boolean hasValidRole = validateRole(user);
log.debug("Valid role: {}", hasValidRole);
// If Valid role create the user else send HTTP 422
if (hasValidRole) {
try {
User users = userRepository.save(new User(
user.getUsername(),
passwordEncoder.encode(user.getPassword()),
user.getRoles(), user.getEmail()));
return new ResponseEntity<>(users, HttpStatus.CREATED);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
} else {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
There are a few important details in here:
Usernames are checked case-insensitively.
Duplicate emails are rejected.
Password complexity is enforced before saving.
Roles are validated against the enum.
Passwords are encoded before the entity is persisted.
The use of ResponseEntity.status(...).build() is intentional in the Boot 4 version. Spring Framework 7 adds ResponseEntity constructors that make new ResponseEntity<>(null, status) ambiguous, so empty responses should use the builder API.
The password validation is intentionally small and explicit:
Password changes are available to admins or to the user changing their own password:
@PreAuthorize(isUser)
@PutMapping("/updatePassword")
public ResponseEntity<User> changePassword(@RequestBody UserInfoDto userInfo) {
if (!isValidPassword(userInfo.password())) {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
// Check if the user is a user with ADMIN
SecurityContext securityContext = SecurityContextHolder.getContext();
boolean isAdminUser = false;
for (GrantedAuthority role : securityContext.getAuthentication().getAuthorities()) {
if (role.getAuthority().contains(ROLE_ADMIN)) {
isAdminUser = true;
}
}
// TODO: Must update the correspondent secret??
// If the username of the authenticated user matches the requestbody username,
// or if it is a user with ROLE_ADMIN
if ((userInfo.username().compareTo(securityContext.getAuthentication().getName()) == 0) || isAdminUser) {
try {
Optional<User> user = userRepository.findByUsername(userInfo.username());
if (user.isPresent()) {
user.get().setPassword(passwordEncoder.encode(userInfo.password()));
userRepository.saveAndFlush(user.get());
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
And the forgot-password flow keeps OTP values hashed too:
@PostMapping("/forgot")
public ResponseEntity<UserInfoDto> createOTP(@RequestBody(required = true) User inUser) {
if (StringUtils.isNotEmpty(inUser.getUsername()) && StringUtils.isNotEmpty(inUser.getOtp())) {
try {
Optional<User> user = userRepository.findByUsernameIgnoreCase(inUser.getUsername());
if (user.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
user.get().setOtp(passwordEncoder.encode(inUser.getOtp()));
userRepository.saveAndFlush(user.get());
return ResponseEntity.status(HttpStatus.OK).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
} else {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
The reset endpoint compares the provided OTP against the stored BCrypt hash:
@PutMapping("/forgot")
public ResponseEntity<?> reset(@RequestBody(required = true) User inUser) {
if (StringUtils.isNotEmpty(inUser.getUsername()) && StringUtils.isNotEmpty(inUser.getOtp())
&& StringUtils.isNotEmpty(inUser.getPassword())) {
if (!isValidPassword(inUser.getPassword())) {
return new ResponseEntity<>("Password does not meet complexity requirements",
HttpStatus.UNPROCESSABLE_ENTITY);
}
try {
Optional<User> user = userRepository.findByUsernameIgnoreCase(inUser.getUsername());
if (user.isEmpty()) {
return new ResponseEntity<>("User does not exist", HttpStatus.NO_CONTENT);
}
if (StringUtils.isEmpty(user.get().getOtp())) {
return new ResponseEntity<>("OTP not generated.", HttpStatus.CONFLICT);
}
if (StringUtils.isEmpty(user.get().getPassword())) {
return new ResponseEntity<>("Password not provided.", HttpStatus.CONFLICT);
}
if (!passwordEncoder.matches(inUser.getOtp(), user.get().getOtp())) {
return new ResponseEntity<>("OTP does not match.", HttpStatus.CONFLICT);
}
if (passwordEncoder.matches(inUser.getPassword(), user.get().getPassword())) {
return new ResponseEntity<>("Password can not be same as previous.", HttpStatus.CONFLICT);
}
user.get().setOtp(null);
user.get().setPassword(passwordEncoder.encode(inUser.getPassword()));
userRepository.saveAndFlush(user.get());
return new ResponseEntity<>("Password successfully changed.",
HttpStatus.OK);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
} else {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
Again, the pattern is the same: accept secret values at the boundary, compare or encode them through Spring Security’s PasswordEncoder, and do not disclose them in responses.
Run Locally
Now let’s run the finished application. This section follows the Run Locally flow from the repository README, because it is the quickest way to prove that Oracle Database is available, Liquibase can create the schema, and the bootstrap users can be created.
Start with an Oracle database that the Liquibase admin user can connect to. For a disposable local Oracle database, you can use the same image family as the integration tests:
docker run --name azn-oracle --rm-p1521:1521
-eORACLE_PASSWORD='LocalSystem123!'
gvenzl/oracle-free:23.26.1-slim-faststart
In another terminal, configure the app. The USER_REPO password is the Oracle schema password that Liquibase assigns to the runtime database user. The bootstrap passwords are application user passwords and will be stored as BCrypt hashes in USER_REPO.USERS.
Now we can walk through the finished code using the Smoke Test API flow from the README. These calls verify that the app is running, the Authorization Server endpoints are exposed, users can authenticate, and an admin can create and update users.
Before we call the API, set up the shell variables used by the walkthrough:
This verifies the basic shape of the running service. Actuator health is available, the unauthenticated ping endpoint works, the authorization server metadata is published, and the JWK endpoint is available for token verification.
The admin user was inserted during startup by the bootstrap initializer. The password came from configuration and was stored in Oracle Database as a BCrypt hash.
If you are rerunning this sequence, remove the sample user first:
This call exercises several things at once. Spring Security authorizes the admin request, the controller validates the role and password, the password is encoded with BCrypt, and JPA stores the user in USER_REPO.USERS.
Verify that the new user can authenticate and use a user endpoint:
That shows the method-security path working. The role stored in Oracle Database changes, Spring Security reads it through the JPA-backed UserDetailsService, and the endpoint authorization follows the updated authorities.
At this point we have an Oracle-backed user repository, Spring Security authentication against that repository, a working user-management API, and Spring Authorization Server issuing tokens.
Test against a real Oracle Database
The integration tests use Testcontainers with Oracle Free:
This is a big benefit of the Oracle Testcontainers support. The tests exercise the actual database behavior: Liquibase, schema creation, identity columns, BCrypt hashes stored in the table, and the Spring Boot datasource configuration.
The authorization server integration test verifies metadata, JWKs, and token issuance:
That is exactly the sort of test I like for this kind of application. It verifies behavior from the outside, and then checks the database-backed repository to confirm the security property we care about: the cleartext password was not stored.
Wrap up
We now have a working Spring Boot 4 authorization server backed by Oracle Database.
Spring Security and Spring Authorization Server give us the authentication framework, filter chains, method-level authorization, password encoding, OAuth2/OIDC endpoints, JWK support, and token issuance. Oracle Database gives us a proper persistent user repository with schema ownership, constraints, audit fields, identity columns, and real integration testing through Testcontainers.
There are a few production topics that deserve their own treatment, especially persistent signing keys, production registered-client storage, wallet-based database connectivity, deployment configuration, and observability. But the core pattern is here: let Spring Security handle security, let Oracle Database handle the durable user store, and keep the boundary between them small and explicit.
The important Spring Boot 4 changes in this version are mostly at the edges: updated starter names, Spring Security 7 package/API moves, Spring Framework 7 response builder usage for empty responses, and Testcontainers 2 artifact names. The application design stays pleasantly boring, which is exactly what I want from a framework upgrade.
]]>https://redstack.dev/2026/05/04/building-an-authorization-server-with-spring-boot-4-and-oracle-database/feed/04317Building an Authorization Server with Spring Boot 3 and Oracle Database
https://redstack.dev/2026/04/30/building-an-authorization-server-with-spring-boot-3-and-oracle-database/
https://redstack.dev/2026/04/30/building-an-authorization-server-with-spring-boot-3-and-oracle-database/#respondFri, 01 May 2026 00:22:09 +0000https://redstack.dev/?p=4307Continue reading →]]>Hi everyone!
In this post I want to show you how to build a small authorization server using Spring Boot, Spring Security, Spring Authorization Server, and Oracle Database. The idea is simple: we want an application that can expose OAuth2/OIDC authorization-server endpoints, authenticate users whose details are stored in Oracle Database, and provide a small REST API for managing those users.
The complete code for this example is in the azn-server repository. In this article we will build it from scratch and look at the important pieces along the way.
One important note before we start: this version of the example is on the Spring Boot 3.x code line. The repository currently uses Spring Boot 3.5.x, Java 21, Spring Authorization Server through the Spring Boot starter, and the Oracle Spring Boot starters. A future post will cover the move to Spring Boot 4.x, including the associated new versions of Spring Framework and Spring Security.
What we are building
The application has three main responsibilities:
Expose OAuth2 and OpenID Connect endpoints using Spring Authorization Server.
Store application users in Oracle Database.
Provide a secured user-management API backed by Spring Security method security.
Spring Security gives us a lot here. It gives us the authentication framework, password encoding, UserDetailsService integration, filter chains, method-level authorization, role hierarchy support, and the authorization-server protocol endpoints. Oracle Database gives us a durable user repository, schema ownership, constraints, identity columns, auditing triggers, and a real database engine for integration tests.
This is the application shape:
Spring Boot starts the service.
Liquibase creates or updates the Oracle schema user.
Liquibase creates the USERS table and audit trigger.
JPA maps the USERS table into a User entity.
Spring Security loads users from that JPA repository.
Spring Authorization Server exposes the OAuth2/OIDC endpoints.
The REST API lets administrators manage users.
Let’s walk through the build.
Create the Spring Boot project
We start with a normal Spring Boot application. The important thing is to include the dependencies for web endpoints, Spring Authorization Server, actuator, JPA, Liquibase, Oracle UCP, Oracle wallet support, and the test stack.
First, spring-boot-starter-oauth2-authorization-server brings in the Spring Authorization Server support that provides the OAuth2/OIDC protocol endpoints. That means we do not have to hand-code token endpoints, metadata endpoints, JWK endpoints, or the protocol filter chain.
Second, the Oracle UCP starter gives us Oracle Universal Connection Pool integration through Spring Boot configuration. That is useful for real services because the database connection pool is not an afterthought – it is part of the application runtime.
Third, Liquibase owns the schema. Hibernate validates the schema, but Liquibase creates it. That is usually the right split for applications where the database is important enough to be managed deliberately.
Configure Oracle Database and Liquibase
The application uses two database identities:
A Liquibase/admin identity that can create and update the application schema.
A runtime schema user named USER_REPO that the application uses for normal database access.
Here is the application configuration:
server:
port: 8080
spring:
application:
name: @project.artifactId@
cloud:
# Discovery is opt-in so local runs and tests do not attempt to register.
discovery:
enabled: ${EUREKA_CLIENT_ENABLED:false}
threads:
virtual:
enabled: true
datasource:
# Runtime connections authenticate directly as the application schema user.
I like this arrangement because the runtime user is not the same as the schema-management user. Liquibase gets the elevated account it needs to create and manage USER_REPO, and the running application connects as USER_REPO. That is a clean security boundary.
That gives us Oracle-aware connection pooling with very little Spring code. We get the operational benefit of a pool that is meant for Oracle Database, while still configuring it in the usual Spring Boot way.
Create the schema with Liquibase
The changelog controller is small:
---
databaseChangeLog:
-include:
file: classpath:db/changelog/dbuser.sql
-include:
file: classpath:db/changelog/table.sql
-include:
file: classpath:db/changelog/trigger.sql
The first changelog creates and maintains the USER_REPO database user:
This is a nice example of letting the database enforce something that belongs in the database. Every update gets audit fields set consistently, whether the update came from this Spring application or from another controlled path later.
Map the Oracle table to a JPA entity
Now we need a JPA entity for the USER_REPO.USERS table.
// Copyright (c) 2023, 2026, Oracle and/or its affiliates.
There are two small but important security choices in this class.
First, password and otp are write-only for JSON serialization. That means the API can accept these values in request bodies, but it will not serialize them back into responses.
Second, Lombok’s @ToString excludes password and otp. That helps prevent secrets from being accidentally written into logs.
The repository is exactly what we want from Spring Data JPA: small, declarative, and focused on the queries the service needs.
// Copyright (c) 2022, 2023, Oracle and/or its affiliates.
This is one of the places where Spring Data JPA shines. The method names communicate intent, Spring implements the queries, and the application code stays readable.
Adapt the database user to Spring Security
Spring Security authenticates with UserDetails. Our database user is a domain object, so we wrap it in a SecurityUser.
// Copyright (c) 2022, 2026, Oracle and/or its affiliates.
This is the bridge between Oracle Database and Spring Security. Once this service exists, Spring Security can authenticate users stored in USER_REPO.USERS.
Configure Spring Security and Spring Authorization Server
The security configuration is the heart of the application. It does several things:
Creates a role hierarchy.
Enables method security.
Creates a dedicated authorization-server filter chain.
Creates a separate actuator filter chain.
Creates a stateless API filter chain.
Provides password encoding.
Provides development/test signing keys.
Optionally creates a local OAuth client.
Here is the role hierarchy:
public static final String ROLE_HIERARCHY = "ROLE_ADMIN > ROLE_USERn"
+ "ROLE_ADMIN > ROLE_CONFIG_EDITORn"
+ "ROLE_CONFIG_EDITOR > ROLE_USER";
/**
* Configure a role hierarchy such that ADMIN "includes"/implies USER.
*
* @return the hierarchy.
*/
@Bean
public RoleHierarchy roleHierarchy() {
return RoleHierarchyImpl.fromHierarchy(ROLE_HIERARCHY);
}
/**
* Configure method security to use the role hierarchy.
*
* @param roleHierarchy injected by Spring.
* @return The MethodSecurityExpressionHandler.
*/
@Bean
public MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setRoleHierarchy(roleHierarchy);
return expressionHandler;
}
Role hierarchy is one of those Spring Security features that is easy to miss but very useful. If an administrator should also be treated as a user, we do not have to duplicate every role check everywhere. We can teach Spring Security that ROLE_ADMIN includes ROLE_USER.
The authorization server gets its own filter chain:
/**
* Authorization Server endpoints use their own filter chain so OAuth protocol
* handling does not inherit API-specific stateless settings.
*
* @param http HttpSecurity injected by Spring.
* @return the SecurityFilterChain.
* @throws Exception if unable to create the chain.
*/
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
throws Exception {
log.debug("In authorizationServerSecurityFilterChain");
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
OAuth2AuthorizationServerConfigurer.authorizationServer();
http
.securityMatcher(authorizationServerConfigurer.getEndpointsMatcher())
.with(authorizationServerConfigurer, authorizationServer ->
authorizationServer.oidc(Customizer.withDefaults()))
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/.well-known/**", "/oauth2/jwks").permitAll()
.anyRequest().authenticated())
.csrf((csrf) -> csrf.ignoringRequestMatchers(authorizationServerConfigurer.getEndpointsMatcher()))
.exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/login"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)));
return http.build();
}
This is where Spring Authorization Server does a lot of heavy lifting. The endpoints matcher identifies the protocol endpoints, OIDC support is enabled, and the well-known metadata and JWK endpoints are allowed anonymously.
The user-management API has a different shape. It is stateless and uses HTTP Basic:
/**
* Create a SecurityFilterChain for the user-management API.
* @param http HttpSecurity injected by Spring.
* @param userDetailsService the JPA-backed user details service.
* @return the SecurityFilterChain.
* @throws Exception if unable to create the chain.
*/
@Bean
@Order(3)
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, UserDetailsService userDetailsService)
throws Exception {
log.debug("In apiSecurityFilterChain");
http
.securityMatcher("/user/api/**", "/error/**")
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/error/**").permitAll()
.requestMatchers("/user/api/v1/ping").permitAll()
.requestMatchers("/user/api/v1/forgot").permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.userDetailsService(userDetailsService);
// The user-management API is stateless and does not use browser sessions or cookies.
http.csrf(csrf -> csrf.disable());
return http.build();
}
The separation between the authorization-server chain and the API chain matters. The OAuth2/OIDC endpoints are protocol endpoints. The user API is a REST API. They have different security needs, so they get different chains.
The authentication provider uses our JPA-backed user details service and a BCrypt password encoder:
/**
* Create an Authentication Provider for our UserDetailsService.
* @param userDetailsService the JPA-backed user details service.
* @param passwordEncoder password encoder for stored password hashes.
* @return the AuthenticationProvider.
*/
@Bean
public DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService,
PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider(userDetailsService);
auth.setPasswordEncoder(passwordEncoder);
return auth;
}
And the password encoder is:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Passwords in the API enter as clear text at the boundary, but they are stored as BCrypt hashes in Oracle Database. That is exactly the line we want: clear text only at the edge, hashes at rest.
For local development and tests, the application can create an opt-in registered client:
/**
* Create an opt-in local client for test and developer-only contexts.
*
* Production deployments should configure registered clients explicitly using
* Spring Boot's authorization-server client properties.
*
* @param passwordEncoder password encoder for the client secret.
* @param clientSecret configured client secret.
* @return a local RegisteredClientRepository.
*/
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "azn.authorization-server.default-client", name = "enabled",
havingValue = "true")
public RegisteredClientRepository localRegisteredClientRepository(PasswordEncoder passwordEncoder,
@Value("${azn.authorization-server.default-client.secret:}") String clientSecret) {
if (!StringUtils.hasText(clientSecret)) {
throw new IllegalStateException("azn.authorization-server.default-client.secret must be set when "
+ "azn.authorization-server.default-client.enabled=true");
}
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("azn-local-client")
.clientSecret(passwordEncoder.encode(clientSecret))
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/azn-local-client")
.scope(OidcScopes.OPENID)
.scope("user.read")
.clientSettings(ClientSettings.builder().requireProofKey(true).build())
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
Notice that this is opt-in. That is intentional. Local convenience is useful, but production registered clients should be configured deliberately.
The JWK source is also local by default:
/**
* Provide process-local signing keys for development and tests.
*
* Production deployments should replace this bean with persistent key material
* so tokens remain verifiable across restarts and rolling deploys.
*
* @return the JWK source.
*/
@Bean
@ConditionalOnMissingBean
public JWKSource<SecurityContext> jwkSource() {
log.warn("Using process-local generated RSA signing keys. Configure a persistent JWKSource bean for "
+ "production so issued tokens remain verifiable across restarts and rolling deploys.");
RSAKey rsaKey = generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
That is fine for development and tests. For production, you would provide persistent signing key material so tokens remain verifiable across restarts and rolling deployments.
Bootstrap the first users
An authorization server needs at least one user to get started. This application creates three bootstrap users on startup by default:
And the implementation creates missing users with BCrypt-encoded passwords:
public static void initUserStore(UserRepository users, PasswordEncoder encoder,
String adminPassword, String userPassword) {
log.debug("ENTER initUserStore");
String obaasAdminPwd = adminPassword;
String obaasUserPwd = userPassword;
String obaasConfigPwd = obaasUserPwd;
// Check for obaas-user, if not existent create the user
if (users.findByUsername(OBAAS_USER).isEmpty()) {
log.debug("Creating user obaas-user");
obaasUserPwd = bootstrapPassword("azn.bootstrap-users.user-password", obaasUserPwd);
users.saveAndFlush(new User(OBAAS_USER, encoder.encode(obaasUserPwd),
"ROLE_USER"));
}
// Check for obaas-admin, if not existent create the user
Optional<User> adminUser = users.findByUsername(OBAAS_ADMIN);
if (adminUser.isEmpty()) {
log.debug("Creating user obaas-admin");
obaasAdminPwd = bootstrapPassword("azn.bootstrap-users.admin-password", obaasAdminPwd);
users.saveAndFlush(new User(OBAAS_ADMIN, encoder.encode(obaasAdminPwd),
"ROLE_ADMIN,ROLE_CONFIG_EDITOR,ROLE_USER"));
}
// Check for obaas-config, if not existent create the user with the same pwd as
// obaas-user
if (users.findByUsernameIgnoreCase(OBAAS_CONFIG).isEmpty()) {
log.debug("Creating user obaas-config");
obaasConfigPwd = bootstrapPassword("azn.bootstrap-users.user-password", obaasConfigPwd);
users.saveAndFlush(new User(OBAAS_CONFIG, encoder.encode(obaasConfigPwd),
"ROLE_CONFIG_EDITOR,ROLE_USER"));
}
}
The bootstrap passwords come from external configuration. If bootstrap users are enabled and the password properties are missing, startup fails:
private static String bootstrapPassword(String propertyName, String configuredPassword) {
if (StringUtils.isNotBlank(configuredPassword)) {
return configuredPassword;
}
throw new IllegalStateException(propertyName + " must be set when azn.bootstrap-users.enabled=true");
}
That is much better than quietly creating default passwords.
@PreAuthorize(isAdminUser)
@PostMapping("/createUser")
public ResponseEntity<?> createUser(@RequestBody User user) {
// If user exists return HTTP Status 409.
Optional<User> checkUser = userRepository.findByUsernameIgnoreCase(user.getUsername());
if (checkUser.isPresent()) {
log.debug("User exists");
return new ResponseEntity<>("User already exists", HttpStatus.CONFLICT);
}
if (!isValidPassword(user.getPassword())) {
return new ResponseEntity<>("Password does not meet complexity requirements",
HttpStatus.UNPROCESSABLE_ENTITY);
}
if (StringUtils.isNotEmpty(user.getEmail())) {
Optional<User> userAlreadyAssociatedWithEMail = userRepository.findByEmailIgnoreCase(user.getEmail());
if (userAlreadyAssociatedWithEMail.isPresent()) {
log.debug("User exists");
return new ResponseEntity<>("Another user exists with same email", HttpStatus.CONFLICT);
}
}
// Validate roles in RequestBody
boolean hasValidRole = validateRole(user);
log.debug("Valid role: {}", hasValidRole);
// If Valid role create the user else send HTTP 422
if (hasValidRole) {
try {
User users = userRepository.save(new User(
user.getUsername(),
passwordEncoder.encode(user.getPassword()),
user.getRoles(), user.getEmail()));
return new ResponseEntity<>(users, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
} else {
return new ResponseEntity<>(null, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
There are a few important details in here:
Usernames are checked case-insensitively.
Duplicate emails are rejected.
Password complexity is enforced before saving.
Roles are validated against the enum.
Passwords are encoded before the entity is persisted.
The password validation is intentionally small and explicit:
Password changes are available to admins or to the user changing their own password:
@PreAuthorize(isUser)
@PutMapping("/updatePassword")
public ResponseEntity<User> changePassword(@RequestBody UserInfoDto userInfo) {
if (!isValidPassword(userInfo.password())) {
return new ResponseEntity<>(null, HttpStatus.UNPROCESSABLE_ENTITY);
}
// Check if the user is a user with ADMIN
SecurityContext securityContext = SecurityContextHolder.getContext();
boolean isAdminUser = false;
for (GrantedAuthority role : securityContext.getAuthentication().getAuthorities()) {
if (role.getAuthority().contains(ROLE_ADMIN)) {
isAdminUser = true;
}
}
// TODO: Must update the correspondent secret??
// If the username of the authenticated user matches the requestbody username,
// or if it is a user with ROLE_ADMIN
if ((userInfo.username().compareTo(securityContext.getAuthentication().getName()) == 0) || isAdminUser) {
try {
Optional<User> user = userRepository.findByUsername(userInfo.username());
if (user.isPresent()) {
user.get().setPassword(passwordEncoder.encode(userInfo.password()));
userRepository.saveAndFlush(user.get());
return new ResponseEntity<>(null, HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
}
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
} else {
return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
}
}
And the forgot-password flow keeps OTP values hashed too:
@PostMapping("/forgot")
public ResponseEntity<UserInfoDto> createOTP(@RequestBody(required = true) User inUser) {
if (StringUtils.isNotEmpty(inUser.getUsername()) && StringUtils.isNotEmpty(inUser.getOtp())) {
try {
Optional<User> user = userRepository.findByUsernameIgnoreCase(inUser.getUsername());
if (user.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
user.get().setOtp(passwordEncoder.encode(inUser.getOtp()));
userRepository.saveAndFlush(user.get());
return new ResponseEntity<>(null,
HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
} else {
return new ResponseEntity<>(null, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
The reset endpoint compares the provided OTP against the stored BCrypt hash:
@PutMapping("/forgot")
public ResponseEntity<?> reset(@RequestBody(required = true) User inUser) {
if (StringUtils.isNotEmpty(inUser.getUsername()) && StringUtils.isNotEmpty(inUser.getOtp())
&& StringUtils.isNotEmpty(inUser.getPassword())) {
if (!isValidPassword(inUser.getPassword())) {
return new ResponseEntity<>("Password does not meet complexity requirements",
HttpStatus.UNPROCESSABLE_ENTITY);
}
try {
Optional<User> user = userRepository.findByUsernameIgnoreCase(inUser.getUsername());
if (user.isEmpty()) {
return new ResponseEntity<>("User does not exist", HttpStatus.NO_CONTENT);
}
if (StringUtils.isEmpty(user.get().getOtp())) {
return new ResponseEntity<>("OTP not generated.", HttpStatus.CONFLICT);
}
if (StringUtils.isEmpty(user.get().getPassword())) {
return new ResponseEntity<>("Password not provided.", HttpStatus.CONFLICT);
}
if (!passwordEncoder.matches(inUser.getOtp(), user.get().getOtp())) {
return new ResponseEntity<>("OTP does not match.", HttpStatus.CONFLICT);
}
if (passwordEncoder.matches(inUser.getPassword(), user.get().getPassword())) {
return new ResponseEntity<>("Password can not be same as previous.", HttpStatus.CONFLICT);
}
user.get().setOtp(null);
user.get().setPassword(passwordEncoder.encode(inUser.getPassword()));
userRepository.saveAndFlush(user.get());
return new ResponseEntity<>("Password successfully changed.",
HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
} else {
return new ResponseEntity<>(null, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
Again, the pattern is the same: accept secret values at the boundary, compare or encode them through Spring Security’s PasswordEncoder, and do not disclose them in responses.
Run Locally
Now let’s run the finished application. This section follows the Run Locally flow from the repository README, because it is the quickest way to prove that Oracle Database is available, Liquibase can create the schema, and the bootstrap users can be created.
Start with an Oracle database that the Liquibase admin user can connect to. For a disposable local Oracle database, you can use the same image family as the integration tests:
docker run --name azn-oracle --rm-p1521:1521
-eORACLE_PASSWORD='LocalSystem123!'
gvenzl/oracle-free:23.26.1-slim-faststart
In another terminal, configure the app. The USER_REPO password is the Oracle schema password that Liquibase assigns to the runtime database user. The bootstrap passwords are application user passwords and will be stored as BCrypt hashes in USER_REPO.USERS.
Now we can walk through the finished code using the Smoke Test API flow from the README. These calls verify that the app is running, the Authorization Server endpoints are exposed, users can authenticate, and an admin can create and update users.
Before we call the API, set up the shell variables used by the walkthrough:
This verifies the basic shape of the running service. Actuator health is available, the unauthenticated ping endpoint works, the authorization server metadata is published, and the JWK endpoint is available for token verification.
The admin user was inserted during startup by the bootstrap initializer. The password came from configuration and was stored in Oracle Database as a BCrypt hash.
If you are rerunning this sequence, remove the sample user first:
This call exercises several things at once. Spring Security authorizes the admin request, the controller validates the role and password, the password is encoded with BCrypt, and JPA stores the user in USER_REPO.USERS.
Verify that the new user can authenticate and use a user endpoint:
That shows the method-security path working. The role stored in Oracle Database changes, Spring Security reads it through the JPA-backed UserDetailsService, and the endpoint authorization follows the updated authorities.
At this point we have an Oracle-backed user repository, Spring Security authentication against that repository, a working user-management API, and Spring Authorization Server issuing tokens.
Test against a real Oracle Database
The integration tests use Testcontainers with Oracle Free:
This is a big benefit of the Oracle Testcontainers support. The tests exercise the actual database behavior: Liquibase, schema creation, identity columns, BCrypt hashes stored in the table, and the Spring Boot datasource configuration.
The authorization server integration test verifies metadata, JWKs, and token issuance:
That is exactly the sort of test I like for this kind of application. It verifies behavior from the outside, and then checks the database-backed repository to confirm the security property we care about: the cleartext password was not stored.
Wrap up
We now have a working Spring Boot 3 authorization server backed by Oracle Database.
Spring Security and Spring Authorization Server give us the authentication framework, filter chains, method-level authorization, password encoding, OAuth2/OIDC endpoints, JWK support, and token issuance. Oracle Database gives us a proper persistent user repository with schema ownership, constraints, audit fields, identity columns, and real integration testing through Testcontainers.
There are a few production topics that deserve their own treatment, especially persistent signing keys, production registered-client storage, wallet-based database connectivity, deployment configuration, and observability. But the core pattern is here: let Spring Security handle security, let Oracle Database handle the durable user store, and keep the boundary between them small and explicit.
In a future post, we will take this example forward to the Spring Boot 4.x line and look at the associated new versions of Spring Framework and Spring Security.
]]>https://redstack.dev/2026/04/30/building-an-authorization-server-with-spring-boot-3-and-oracle-database/feed/04307Building a Spring Boot Starter for Oracle Spatial
https://redstack.dev/2026/04/02/building-a-spring-boot-starter-for-oracle-spatial/
https://redstack.dev/2026/04/02/building-a-spring-boot-starter-for-oracle-spatial/#respondThu, 02 Apr 2026 18:41:00 +0000https://redstack.dev/?p=4299Continue reading →]]>Hi everyone!
Over the last few days I have been working on a new Spring Boot starter for Oracle Spatial. I did this work with two other real developers, and three AI coding assistants, and I thought it would be interesting to write up the story of how it came together.
This was a good example of how building a starter is not just about getting code to compile or getting a sample app to run. It is also about API shape, developer expectations, reviewer feedback, naming, documentation, tests, and all of those little choices that decide whether something feels natural or awkward once another developer actually tries to use it.
We ended up in a much better place than where we started, but not because the first design was perfect. We got there because the reviews were good, the feedback was honest, and we were willing to change direction once it was clear the API could be better.
So this post is a bit of a behind-the-scenes look at that process.
What we were trying to build
The goal sounded simple enough on paper:
create a Spring Boot starter for Oracle Spatial
make it easy to work with SDO_GEOMETRY
keep the programming model GeoJSON-first
provide a sample application that shows realistic use
The kinds of queries we had in mind were the kinds of queries almost everyone reaches for first:
store a point or polygon
fetch it back as GeoJSON
find landmarks near a point
find landmarks within or interacting with a polygon
So from the beginning this was going to involve Oracle Spatial operators such as:
SDO_UTIL.FROM_GEOJSON
SDO_UTIL.TO_GEOJSON
SDO_FILTER
SDO_RELATE
SDO_WITHIN_DISTANCE
SDO_NN
SDO_GEOM.SDO_DISTANCE
We also wanted a sample app that felt approachable. We used a small San Francisco landmark dataset so the sample would be easy to understand and a little bit fun to play with.
Where we started
The first version of the starter leaned in the direction that I think a lot of us would naturally start with: helper utilities.
We had one piece focused on converting GeoJSON to and from Oracle Spatial, and another piece focused on generating the bits of SQL you need for common spatial predicates and projections.
On one level, that worked.
It absolutely solved real problems:
you did not have to remember the exact SDO_UTIL.FROM_GEOJSON(...) call
you did not have to hand-type the common predicate shapes every time
you could centralize the default SRID and distance unit
If you already like building SQL with JdbcClient, it was useful.
But there was a catch. The public API was still basically returning strings. And once that got called out in review, it was hard to ignore.
The review comment that changed everything
The most important reviewer comment was not about a syntax error or a missing test. It was about the shape of the API.
The feedback was basically: if this is a Spring Boot starter, why is the main experience a SQL string builder?
That was the right question.
It is one thing to have Spring-managed beans. It is another thing entirely to have a Spring-native programming model.
At that point the starter was Spring-managed, but not really Spring-native. Yes, you could inject the beans, but what you got back were still string fragments that you had to splice together yourself.
That triggered the main redesign.
The moment that made the redesign easier
One thing that helped a lot is that the original API had not been released yet.
That is a huge advantage.
It meant we did not need to protect old method names or preserve an API shape just because it already existed. We were free to ask a better question: if we were designing this from scratch for Spring developers, what should it look like?
Once we reframed it that way, the answer became much clearer.
What we changed
The big change was moving away from public string-builder beans and toward one main Spring JDBC integration bean:
OracleSpatialJdbcOperations
Instead of treating Oracle Spatial as a collection of string helper methods, we moved to a design where application code injects one bean and then creates typed spatial query parts:
SpatialGeometry
SpatialExpression
SpatialPredicate
SpatialRelationMask
This ended up being a much better fit for the way Spring JDBC code is usually written.
You still write SQL. We did not try to invent a whole DSL. But the spatial pieces now carry more meaning and stay connected to the bind process instead of floating around as anonymous fragments.
That was the key design improvement.
Why this felt better almost immediately
One of the things I liked about the redesign is that the sample application got better almost immediately once the API got better.
That is usually a good sign.
When an API is awkward, the sample tends to look awkward too. You can hide that for a little while, but not for long.
With the redesigned API, the service code started to read much more naturally. In the sample’s findNear flow, for example, we now create:
a SpatialGeometry
a distance expression
a within-distance predicate
and then build the SQL around those named pieces.
That may sound like a small thing, but it makes a big difference when someone is reading the sample for the first time and trying to understand the intended usage pattern.
Instead of “here is some mysterious Oracle SQL,” the code reads more like “here is the geometry we are searching around, here is the distance we want to project, and here is the predicate we want to apply.”
That is a much better teaching story.
The sample app became part of the design process
I think sometimes people talk about sample applications as though they are just an afterthought. In practice, for a starter like this, the sample is part of the design process.
It answers questions like:
does the API feel natural in a real service?
are the method names understandable?
can we explain this to somebody without too much ceremony?
does the code read like Spring, or does it read like a thin wrapper over raw SQL?
Our sample app is a simple REST service built around landmarks in San Francisco.
It has endpoints for:
creating a landmark
fetching a landmark by id
finding nearby landmarks
finding landmarks inside or interacting with a polygon
We also spent some time improving the seed data because I wanted the sample to be a little more recognizable and useful. So the sample now includes landmarks like:
Ferry Building
Union Square
Golden Gate Park
Oracle Park
Salesforce Tower
Transamerica Pyramid
Coit Tower
That may not be the most “architectural” part of the work, but it helps make the sample feel real instead of abstract.
One small enum that mattered more than I expected
Another design decision that turned out to matter a lot was replacing raw relation-mask strings with an enum:
SpatialRelationMask
This came directly out of review feedback.
The problem with raw strings is obvious once someone points it out: a developer can type something like "INTERSECTS" and everything looks fine until runtime, when Oracle tells them that is not a valid mask.
That is exactly the kind of thing a good starter should help with.
By introducing an enum, we made that part of the API:
safer
easier to discover
harder to misuse
It is a small API element, but it made the whole thing feel more deliberate.
Distance became first-class because it had to
One of the early reviews also pointed out that if we wanted to serve real spatial use cases, we needed first-class support for distance calculations.
That was absolutely right.
A lot of real applications want some version of:
find nearby things
return the distance
order by distance
If the starter handled filtering but not distance calculation, it would always feel like it stopped just short of the most useful scenario.
So SDO_GEOM.SDO_DISTANCE became part of the main API design rather than something developers would have to improvise themselves.
I think that made the starter much more credible for real use.
Documentation ended up being more important than I expected
I do not mean that in a generic “docs matter” way. I mean that for this starter in particular, the documentation had to explain a mental model, not just list methods.
The most useful documentation change we made was adding a clear distinction between:
what gets injected as a Spring bean
what gets created per query
That turned out to be the right way to explain the design.
You inject:
OracleSpatialJdbcOperations
And then per query you create:
SpatialGeometry
SpatialExpression
SpatialPredicate
Once we started explaining it that way, the docs got much easier to follow.
We also added concrete query pattern examples for:
inserts
GeoJSON projection
filter + relate
distance-ordered proximity queries
Those examples matter because they show how the design is actually supposed to be used. For a starter, that is every bit as important as the Javadoc.
Some of the polish came from the less glamorous review comments
Not all of the useful review feedback was high-level architecture. Some of it was the kind of practical feedback that makes software much more solid.
A few examples:
The sample needed better error handling
At one point the sample app would throw an exception and return a 500 if a caller passed an invalid spatial relation mask.
That is a perfectly believable bug in a sample. It is also exactly the kind of thing a reviewer should call out, because the sample is part of the product story.
We fixed it so that invalid masks now produce a proper 400 Bad Request with a useful message.
The tests needed to be more Spring-native too
We got feedback to use @ServiceConnection in the Testcontainers-based tests, and that was good advice. It made the tests more consistent with current Spring Boot style and reduced some manual wiring.
We also adjusted the integration test to run as the app user rather than system, which is a much better representation of how the code should actually work.
The SQL setup needed to be repeatable in CI
This is one of those things that only becomes obvious once CI starts yelling at you.
We hit issues with setup SQL being run more than once and colliding with existing objects or metadata. That led to a round of cleanup to make the test setup more idempotent and more robust.
That is not the glamorous part of building a starter, but it is absolutely part of shipping one.
What we deliberately did not do
There were also some things we chose not to do in this round of work.
I think that is worth talking about because saying “not yet” is often part of good design.
We did not try to eliminate SQL entirely
Even after the redesign, application code still assembles SQL statements with JdbcClient.
That was intentional.
We wanted to make the API more Spring-native, but not disappear into a custom DSL or pretend SQL no longer exists. This is still Spring JDBC. SQL is still the right abstraction level. The important improvement was to stop making the public API itself a string-builder API.
There is still room to improve the ergonomics in the future, especially around making it harder to forget a bind contributor. Reviewers called that out too, and I think they are right. But that felt like a v2 refinement, not something we needed to solve before this version was useful.
We did not add every possible spatial operation
Another good review point was that buffer generation would be useful too. I agree.
But once again, that felt like feature expansion rather than a cleanup item for this iteration.
There is always a temptation to keep adding one more thing once the codebase is open and fresh in your mind. In this case I think the right move was to get the core API shape right, get the sample and docs into good condition, and leave some room for future work.
What I think we ended up with
At the end of all of this, what we have is not just a set of helper methods. It is a small but coherent Spring Boot story for Oracle Spatial.
The final result includes:
a starter that auto-configures a Spring JDBC-oriented spatial bean
a typed API for spatial query parts
safer handling of SDO_RELATE masks
first-class distance support
a sample REST app that demonstrates realistic usage
docs that explain the mental model, not just the method list
integration tests that run against Oracle AI Database 26ai Free with Testcontainers
And maybe the biggest thing for me is that it now feels like something I would want another Spring developer to pick up and try.
That was not as true of the first version.
What we are already thinking about for v2
Even though I feel good about where this landed, we have also been pretty careful to write down the things that did not belong in this iteration.
There are at least two clear areas for a possible v2.
The first is improving the ergonomics around binding and query composition.
Right now the design is much better than the original string-builder approach, but there is still a pattern like this:
That is a reasonable place to be for a JDBC-oriented starter, but it is not hard to imagine a future version that tightens that up further and makes it harder to forget a bind contributor.
The second is expanding the supported spatial operations.
One of the most obvious candidates there is buffer generation with SDO_GEOM.SDO_BUFFER. That came up during review, and I think it is a very good candidate for a future enhancement. There are also broader questions about whether repository-style integrations or richer mapping options might make sense once we have real experience with how people use the current API.
But I want to be careful here. Just because we can imagine a v2 does not mean we should rush into it. What I would really like at this point is to get feedback from actual users first.
I would much rather learn from people who try the starter on real spatial workloads than guess too aggressively about what the next abstraction should be. Maybe the next thing we need is buffer support. Maybe it is better row mapping. Maybe it is a tighter JdbcClient integration. Maybe it is something we have not even thought about yet.
So yes, we do have a v2 plan taking shape. But before we take that next step, I would love to hear from users and see how this first version holds up in practice.
Working with AI coding assistants
Like many people today, I am doing more and more work with AI Coding assistants. For this piece of work, these are the participants and the roles they played:
me: collaborated with GPT to write the specification, set the standards, conventions, etc., guided the whole process, read and reviewed code myself, helped make, or made design decisions
GPT-5.4: acted as the primary developer, wrote most of the code, reflected on its own work, helped write and refine the specification, processed review comments and planned, helped with the design
Claude Code: acted as a “senior architect” who reviewed the code with a focus on technical aspects and gave detailed feedback and recommendations
Gemini (3 thinking/pro): acted as the “product manager” who reviewed the project from the point of view of how well it addressed the need, if it exposed the right features and capabilities, and how useful it would be for a spatial user
two human colleagues: acted as reviewers and developers who provided valuable feedback on the code and the design
As we worked through the project together, I saved a lot of the generated plans and reviews in the .ai directory because I think those are valuable artifacts. We’re obviously using AI more, and we have no intention of hiding it, so why not save these for future use? Seems like the right thing to do. We did have a conversation about this before coming to the conclusion that we should save them and put them in the public repo.
I also want to mention that there were several cycles in the project. We started discussing the requirements and writing a plan. We reviewed this and iterated on it two or three times before we ever started writing any code. By “we”, I mean me and the three AIs. It was interesting to see the slightly different opinions of the AIs and the different areas they focused their attention on. Just like human developers, the different opinions and insights were useful to help us get to a better result.
After we started development, we continued to cycle through reviews, feedback, updates. At one point, as discussed above, we decided to redesign – this was a result of human feedback. The AIs certainly did a good job, and they are getting better all the time, but I do still feel that they are not as good at doing novel things as they are at doing things that have been done before, and they perhaps don’t consider (or at least mention) the implications of architectural decisions as much as some human developers do, at least in my experience to date. But I am sure they will continue to evolve rapidly.
I guess I’d just say – if you have not tried working in a team with multiple AI coding assistants yet, give it a go!
Why I wanted to write this up
I wanted to tell this story because I think it is a pretty normal and healthy example of how good API work actually happens.
You start with an idea.
You build something that is useful but not yet quite right.
Somebody asks a question that exposes the weakness in the design.
You resist it for a minute.
Then you realize they are right.
Then the real design work starts.
That is basically what happened here.
And I think the result is better precisely because we were willing to let the reviews change the direction of the code rather than just polish the original design.
Wrapping up
I am really happy with how this turned out.
Not because it is finished forever. It is not. There are still good future directions here. But the core design now feels solid, and the sample, tests, and docs all tell a coherent story.
That is what I wanted from this starter.
If you are working with Spring Boot and Oracle Database, and you have spatial use cases in mind, I think this gives you a pretty nice starting point. And if you are designing your own starter or library, maybe the bigger lesson here is that reviewer feedback is not just something to “address.” Sometimes it is the thing that helps you find the real design.
More on this soon.
]]>https://redstack.dev/2026/04/02/building-a-spring-boot-starter-for-oracle-spatial/feed/04299Building a Simple Spatial Web App with the New Spring Boot Starter for the Spatial Features in Oracle AI Database 26ai
https://redstack.dev/2026/04/01/building-a-simple-spatial-web-app-with-the-new-spring-boot-starter-for-the-spatial-features-in-oracle-ai-database-26ai/
https://redstack.dev/2026/04/01/building-a-simple-spatial-web-app-with-the-new-spring-boot-starter-for-the-spatial-features-in-oracle-ai-database-26ai/#respondWed, 01 Apr 2026 21:38:09 +0000https://redstack.dev/?p=4262Continue reading →]]>Hi everyone!
In this post, I will show how to run the new Spring Boot starter for the Spatial features in Oracle AI Database 26ai by using the sample application and connecting it to a simple web application front end.
The starter makes it easier to build Spring Boot applications that work with Oracle Spatial data and expose that data through familiar REST APIs. For this example, I am using Oracle AI Database 26ai Free, the Spatial sample application from the Spring Cloud Oracle repository, and a small React front end that displays landmark data on a map.
The app will do three things:
load landmarks inside an initial San Francisco polygon
find the nearest landmarks to a point you click on the map
search the landmarks inside the current visible map area
The Spring Boot starter for the Spatial features in Oracle AI Database 26ai is a v1 release, and I want to say that clearly up front. If you build spatial applications with Spring Boot and Oracle Database, I would really love feedback on what works well, what feels awkward, and what you would want to see next.
A few important things to note before we get into the code:
the work is merged into main
the new starter artifacts may still be ahead of the next Maven Central release
for this walkthrough, I am running the sample application from a source checkout of the spring-cloud-oracle repository
That last point matters because I want to give you steps you can run today, not steps that depend on a release that may not have shipped yet.
Before You Begin
For this walkthrough, you will need:
Java 21 or newer
Maven
Node.js and npm
Docker
a local checkout of the spring-cloud-oracle repository
a local checkout of this frontend companion repository
You will also need Oracle AI Database 26ai Free running locally.
If you already have Oracle AI Database 26ai Free running and you already have a user/schema you want to use for testing, you can adapt the setup below. I am going to show the exact steps that worked for me from a clean local environment.
Start Oracle AI Database 26ai Free
Before you run the container, sign in to Oracle Container Registry and accept the Oracle terms for the Oracle AI Database 26ai Free image. If you skip that step, the image pull may fail with an authentication or authorization error.
Then start Oracle AI Database 26ai Free in a container:
The first startup will take a few minutes. You can check the logs to see when startup is complete:
docker logs -f oracle-free
Wait until you see the message DATABASE IS READY TO USE before continuing.
Create the Sample User
For local testing, the sample worked most reliably when I created a dedicated user for it and granted the permissions needed for the spatial objects and index.
Connect as the system user and run:
create user spatialsample identified by spatialsample;
grant create session to spatialsample;
grant create table to spatialsample;
grant create view to spatialsample;
grant create sequence to spatialsample;
grant create procedure to spatialsample;
grant unlimited tablespace to spatialsample;
grant create indextype to spatialsample;
grant create operator to spatialsample;
grant execute on mdsys.sdo_geometry to spatialsample;
grant execute on mdsys.sdo_util to spatialsample;
grant execute on mdsys.sdo_geom to spatialsample;
grant execute on mdsys.sdo_cs to spatialsample;
grant execute on mdsys.spatial_index_v2 to spatialsample;
I am calling this out explicitly because this is one of the places where a setup detail can quietly derail the rest of the sample. Creating the user and grants up front made the rest of the walkthrough much more predictable.
The explicit grant execute on mdsys.spatial_index_v2 may look a little unusual at first glance, but it is there for a reason. Oracle’s Spatial index documentation calls out the need for EXECUTE privilege on the index type and its implementation type when creating a spatial index.
Create the Schema and Seed Data
Next, connect as the new spatialsample user and set up the schema and initial sample data:
This is one of those places where I think being explicit helps. It is very easy to gloss over schema setup in a sample, but for Oracle Spatial this part is important:
the table exists
the geometry metadata exists
the spatial index exists
the sample data is already in place
Without those pieces, the rest of the walkthrough is much harder to follow.
I also like this version of the setup script because it is easier to rerun while you are testing locally. It clears the metadata entry and seed data before recreating the parts of the sample that need to be there.
Run the Official Sample Application
The backend for this walkthrough is the official sample application from the Spring Cloud Oracle repository.
The command that worked reliably for me was:
cd ~/spring-cloud-oracle/database/starters/oracle-spring-boot-starter-samples/oracle-spring-boot-sample-spatial
Note that I split that string for readability, but you need to put it all on one line!
There are two details here that are worth calling out:
I ran the command from the sample module directory
passing the datasource properties through spring-boot.run.arguments was the most reliable local approach
That is worth preserving exactly. I tried a couple of other ways to pass the datasource values, and this was the one that consistently worked for me.
If that starts cleanly, the sample backend should now be listening on http://localhost:9002.
What the Sample Already Gives Us
Before I write any frontend code, it is worth looking at what the sample already gives us.
The REST API is small and very easy to explain:
POST /landmarks
GET /landmarks/{id}
GET /landmarks/near
POST /landmarks/within
That is a useful shape for a tutorial because it is already enough to demonstrate:
GeoJSON in and GeoJSON out
nearest-neighbor style point searches
polygon-based area searches
Add Local CORS for the Frontend
When I first tried to connect the frontend to the sample application, I hit a CORS problem. For local development, the fix was to add @CrossOrigin to LandmarkController.java in the sample application.
@CrossOrigin(origins = "http://localhost:5173")
@RestController
public class LandmarkController {
// ...
}
This is just for local development. I would not copy this unchanged into a production application.
Also, if you skip this and go straight to the frontend, the browser error is not especially helpful. You will usually just see a generic “failed to fetch” style error when the request to /landmarks/within gets blocked.
Smoke-Test the REST API
Before building the frontend, I like to make sure the API is behaving the way I expect.
Let’s start with a few direct calls to the sample backend.
A simple lookup by id:
curl http://localhost:9002/landmarks/1
A nearest-neighbor style request using a compact GeoJSON point in the query string:
At this point, it is useful to verify that the backend is returning the kind of data we expect before moving on to the browser. The following example shows the API working from the command line.
If these calls work, the rest of the article gets a lot simpler. At that point, we know the database is up, the sample app is talking to it, and the spatial endpoints are behaving before the browser gets involved.
The Frontend Project
For the UI, I used a separate React application built with Vite, TypeScript, and React Leaflet.
Here is the full layout of the web directory before I walk through the main pieces:
I kept this frontend separate from the sample app because it makes the browser-side behavior easier to explain, and it is a very common setup that most people will recognize immediately.
I also like this split for demo applications because it keeps the browser code and the backend code easy to reason about independently.
Start the Frontend
In this frontend project, start the development server like this:
cd ~/spatial-starter-v1-blog/web
VITE_API_BASE_URL=http://localhost:9002 npm run dev
By default, Vite runs on http://localhost:5173, which is why that is the origin I allowed in the local CORS annotation above.
The Initial Map Load
For the initial screen, I did not want a generic “list all landmarks” endpoint. Since this is a spatial application, I wanted the initial load to already be spatially scoped.
So instead, I defined an opening polygon for a useful part of San Francisco:
north: Fisherman’s Wharf
east: Oracle Park
south: Mission
west: the western edge of Golden Gate Park
In the frontend, that polygon is just a small GeoJSON object:
constINITIAL_WEST=-122.515;
constINITIAL_EAST=-122.35;
constINITIAL_SOUTH=37.75;
constINITIAL_NORTH=37.808;
exportconstinitialSearchPolygon={
type:"Feature",
properties:{
label:"Initial San Francisco search area"
},
geometry:{
type:"Polygon",
coordinates:[[
[INITIAL_WEST,INITIAL_SOUTH],
[INITIAL_EAST,INITIAL_SOUTH],
[INITIAL_EAST,INITIAL_NORTH],
[INITIAL_WEST,INITIAL_NORTH],
[INITIAL_WEST,INITIAL_SOUTH]
]]
}
};
Then I post that polygon to /landmarks/within with the ANYINTERACT mask.
That gives the initial screen a much more natural map behavior. Instead of “show me everything,” the app starts with “show me the landmarks in this area.”
One small helper worth showing here is geometryToString. The sample accepts the geometry field as a JSON string, not as a nested object, so the frontend needs to serialize the GeoJSON before sending it.
Once the initial polygon query is wired up, the application starts with a focused view of San Francisco and only the landmarks that fall inside that opening search area.
Rendering Points and Polygons
One of the nice things about the sample is that the API boundary stays GeoJSON-first. That means the frontend does not need a special Oracle representation. It can just parse the returned GeoJSON and render it.
I render polygon landmarks with GeoJSON, and point landmarks with CircleMarker.
That makes the search feel much more obvious when you use the map.
It is a small detail, but it makes the demo much easier to understand visually. You can immediately see both the point you picked and the radius you asked the backend to search within.
The screenshot below shows that interaction in context, with the selected point on the map and the search radius drawn around it.
Search the Visible Area
The other interaction I wanted was the ability to search the current map area.
For that, I turn the map bounds into a polygon and post it to /landmarks/within:
ANYINTERACT returns any landmark that touches or overlaps the search polygon, which is useful when a geometry sits on the edge of the visible area. INSIDE returns only landmarks whose geometry falls entirely within the polygon.
After panning the map and running the visible-area query, the UI updates to reflect the current viewport instead of the original startup polygon.
Why the GeoJSON Boundary Matters
There are a few reasons I like this sample as a starting point.
First, the sample stays GeoJSON-first at the API boundary. That is exactly what I want for browser-facing map work.
Second, the backend makes the spatial queries feel very normal from a Spring developer perspective. You are still building a simple REST application, not learning a whole new framework just to use Oracle Spatial.
Third, the v1 scope feels very reasonable. It gives me enough to build real point and polygon workflows, and it gives me something concrete to build on without trying to solve every spatial use case at once.
That said, this is also why I would really like feedback from people who actively use Oracle Spatial and Spring Boot. The best next steps will probably come from the people doing this work for real.
Wrapping Up
For this example, I used the new Oracle Spatial Spring Boot sample as the backend, then layered a small React + Leaflet application on top of it to:
load a meaningful initial area
search for nearby landmarks from a clicked point
query landmarks inside the current visible map area
The part I like most is that nothing about the frontend had to become Oracle-specific. The browser stayed in GeoJSON and map primitives, which is exactly where I want it.
For a Spring developer, that is one of the most useful parts of this v1 starter. It makes it much easier to work with spatial data in a normal Spring Boot application without having to invent the basic plumbing first.
If you are using Oracle Spatial with Spring Boot, I would genuinely love feedback on what works well, what feels awkward, and what you would want to see next.
]]>https://redstack.dev/2026/04/01/building-a-simple-spatial-web-app-with-the-new-spring-boot-starter-for-the-spatial-features-in-oracle-ai-database-26ai/feed/04262Exploring some new Helidon features – Data Repositories and SE Declarative
https://redstack.dev/2026/03/05/exploring-some-new-helidon-features-data-repositories-and-se-declarative/
https://redstack.dev/2026/03/05/exploring-some-new-helidon-features-data-repositories-and-se-declarative/#commentsFri, 06 Mar 2026 01:58:29 +0000https://redstack.dev/?p=4251Continue reading →]]>With Helidon 4.4.0 right around the corner, I’ve been spending some time playing with the latest milestone release (4.4.0-M2). If you haven’t been following along, Helidon 4 was a major milestone because it was the first framework built from the ground up on Java 21 virtual threads.
Now, with 4.4, we are seeing some really cool incubating features becoming more stable inlcuding Helidon Data Repositories, Helidon SE Declarative and Helidon AI. I am working on a sample project called Helidon-Eats to show how these work together. In this installment, I am looking at the first two.
The “No-Magic” Power of Helidon SE Declarative
If you’ve used Helidon MP (MicroProfile), or if you are more familiar with Spring Boot’s Inversion of Control approach (like me), then you’re used to the convenience of dependency injection and annotations. Helidon SE, on the other hand, has always focused on transparency and avoiding “magic.” While that’s great for performance, it usually meant writing more boilerplate code to register routes and manage services manually.
Helidon SE Declarative changes that. It gives you an annotation-driven model like MP, but here is the trick: it does everything at build-time. Using Java annotation processors, Helidon generates service descriptors during compilation. This means you get the clean, injectable code you want, but without the runtime reflection overhead that slows down startup and eats memory. Benchmarks have even shown performance gains of up to +295% over traditional reflection-based models on modern JDKs. (see this article)
Now, to be completely fair, I will say that I am not completely sold on the build-time piece yet. For example, the @GenerateBinding annotation (if I am not mistaken) causes an ApplicationBinding class to be generated at build time, and that lives in your target/classes directory. I found during refactoring that you have to be careful to mvn clean each time to make sure it stays in sync with your code, just doing a mvn compile or package could get you into trouble. And I am not sure I am happy with it not being checked into the source code repository. But, I’ll withhold judegment until I have worked with it a bit more!
Simplifying Persistence with Helidon Data
The Helidon Data Repository is another big addition. It’s a high-level abstraction that acts as a compile-time alternative to heavy runtime ORM frameworks. Instead of writing JDBC code, you define a Java interface, and Helidon’s annotation processor generates the implementation for you.
It supports standard patterns like CrudRepository and PageableRepository, which I used in this project to handle the recipe collection. The framework can even derive queries directly from your method names (like Spring Data does) – so a method like findById is automatically turned into the correct SQL at build-time.
The Backend: Oracle AI Database 26ai
For this sample, I’m using Oracle AI Database 26ai Free. I sourced some public domain recipe data from Kaggle that comes as a line-by-line JSON file (LDJSON).
Normally, if you want to store hierarchical JSON in relational tables, you have to write complex mapping logic in your application. But I wanted to try a more novel approach using JSON Relational Duality Views (DV).
Duality Views are a game-changer because they decouple how data is stored from how it is accessed. My data is stored in three normalized tables (RECIPE, INGREDIENT, and DIRECTION) which ensures ACID consistency and no data duplication. The database can surface this data to applications as a single, hierarchical JSON document. I am not using that feature in this post, but I will in the future!
GraphQL-Based View Creation and Loading
One of the coolest parts of Oracle AI Database 26ai is that you can define these views using a GraphQL-based syntax . The database engine automatically figures out the joins based on the foreign key relationships.
Isn’t that just the cleanest piece of SQL that deals with JSON that you’ve ever seen?
Because the view is “updatable” (@insert, @update), I used it to actually load the data. Instead of a complex ETL process, my startup script just reads the LDJSON file line-by-line and does a simple SQL insert directly into the view. The database engine takes that single JSON object and automatically decomposes it into rows for the three underlying tables.
Modeling the Service
On the Java side, I modeled the Recipe entity to handle the parent-child relationships using standard @OneToMany collections.
One detail I want to highlight is the use of @JsonbTransient. When you build a REST API, you often have internal metadata like database primary keys or sort ordinals that you don’t want messing up the JSON that the end user gets to see. By annotating those fields with @JsonbTransient, they are excluded from the final JSON response. This keeps the API response clean and focused only on the recipe data.
@Entity
@Table(name = "RECIPE")
public class Recipe {
@Id
@Column(name = "ID")
private Long recipeId;
private String recipeTitle;
@JsonbTransient
private Long internalId; // Hidden from the API
@OneToMany(mappedBy = "recipe")
private List<Ingredient> ingredients;
//...
}
In the repository object, you can use the method naming conventions to automatically create queries (like Spring Data) and you can also write your own JPQL (not SQL) queries, as I did in this case (also like Spring Data):
The configuration is handled in the application.yaml, where I point Helidon to the Oracle instance using syntax that again is very reminiscent of what I’d do in Spring Boot.
With Declarative SE, injecting the repository into my endpoint is simple. I just use @Service.Inject on the constructor, which allows me to keep my fields private final.
@Service.Singleton
@Http.Path("/recipe")
public class RecipeEndpoint {
private final RecipeRepository repository;
@Service.Inject
public RecipeEndpoint(RecipeRepository repository) {
this.repository = repository;
}
@Http.GET
@Http.Path("/{id}")
public Optional<Recipe> getRecipe(Long id) {
return repository.findById(id);
}
}
Finally, the Main class uses @Service.GenerateBinding. This tells the annotation processor to generate the “wiring” code that starts the server and initializes the service registry without needing to scan the classpath at runtime.
@Service.GenerateBinding
public class Main {
public static void main(String args) {
LogConfig.configureRuntime();
ServiceRegistryManager.start(ApplicationBinding.create());
}
}
In this context, the “service registry” is something in Helidon that keeps track of the services in the application and handles injection and so on. It’s a lot like the way Spring Boot scans for beans and wires/injects them where needed.
The Result
When you hit the service, you get a clean, well structured JSON response that masks all the complexity of the underlying three-table relational join.
Example Response for http://localhost:8080/recipe/22387:
{
"category": "Appetizers And Snacks",
"description": "I came up with this rhubarb salsa while trying to figure out what to do with an over-abundance of rhubarb...",
"directions":,
"ingredients": [
"2 cups thinly sliced rhubarb",
"1 small red onion, coarsely chopped",
"3 roma (plum) tomatoes, finely diced"
],
"recipeId": 22387,
"recipeTitle": "Tangy Rhubarb Salsa",
"subcategory": "Salsa"
}
Wrap Up
Helidon 4.4 is making the SE flavor feel a lot more like a high-productivity framework without sacrificing performance. By shifting the data transformation logic to the database with Duality Views and using build-time code generation for injection, we can build services that are both incredibly fast and easy to maintain.
Now, you may have noticed that I said “like Spring” a lot in this post – and that’s because of two things – I do happen to use Spring a lot more than I use Helidon, and I like it. So I am very happy that Helidon is looking more like Spring, it makes it a lot easier to switch between the two, and I think it lowers the barrier to entry for people who are coming from the Spring world.
Grab the code from the Helidon-Eats repo and let me know what you think – and stay tuned for the next steps as I explore Helidon AI!
]]>https://redstack.dev/2026/03/05/exploring-some-new-helidon-features-data-repositories-and-se-declarative/feed/14251Using Reflection to Help LLMs Write Better SQL
https://redstack.dev/2025/11/12/using-reflection-to-help-llms-write-better-sql/
https://redstack.dev/2025/11/12/using-reflection-to-help-llms-write-better-sql/#respondWed, 12 Nov 2025 22:18:47 +0000https://redstack.dev/?p=4244Continue reading →]]>Getting LLMs to write good SQL can be tricky. Sure, they can generate syntactically correct queries, but do those queries actually answer the question you asked? Sometimes an LLM might give you technically valid SQL that doesn’t quite capture what you’re really looking for.
I wanted to experiment with the reflection pattern to see if we could get better results. The idea is simple: after the LLM generates SQL and executes it, have it reflect on whether the query actually answers the original question. If not, let it try again with the benefit of seeing both the question and the initial results.
Let me show you how this works.
Setting up the database
I used an Oracle Autonomous Database on Oracle Cloud for this experiment. First, I created a user with the necessary permissions. Connect as ADMIN and run this:
create user moviestream identified by <password>;
grant connect, resource, unlimited tablespace to moviestream;
grant execute on dbms_cloud to moviestream;
grant execute on dbms_cloud_repo to moviestream;
grant create table to moviestream;
grant create view to moviestream;
grant all on directory data_pump_dir to moviestream;
grant create procedure to moviestream;
grant create sequence to moviestream;
grant create job to moviestream;
Next, let’s load the sample dataset. Still as ADMIN, run this:
Then connect as the moviestream user and run this to load the rest of the dataset:
BEGIN
workshop.add_dataset(tag => 'end-to-end');
END;
/
This takes a few minutes to complete, after which we have a database with customer and sales data to work with.
The approach
The reflection pattern works like this:
Give the LLM the database schema and a natural language question
LLM generates SQL (v1)
Execute the SQL and get results
LLM reflects: “Does this SQL actually answer the question?”
Generate improved SQL (v2) based on the reflection
Execute v2 and provide the final answer
The key insight here is that by seeing the actual results, the LLM can judge whether it interpreted the question correctly. For example, if you ask “who are our top customers?”, the LLM might initially think “highest income” when you actually meant “highest spending”. Seeing the results helps it course-correct.
Setting up the Python environment
I used a Jupyter notebook for this experiment. First, let’s install the libraries we need:
%pip install aisuite oracledb
I’m using Andrew Ng’s aisuite for a unified interface to different LLM providers, and oracledb to connect to the database.
Now let’s import aisuite:
import aisuite as ai
Connecting to Oracle Autonomous Database
For Oracle Autonomous Database, you’ll need to download the wallet and set up the connection. Here’s how I connected:
For the LLM to write good SQL, it needs to know what tables and columns are available. Let’s write a function to introspect the schema:
def get_schema():
stmt = f'''
SELECT
utc.table_name,
utc.column_name,
utc.data_type,
utc.data_length,
utc.nullable,
utc.column_id,
ucc.comments AS column_comment,
utab.comments AS table_comment
FROM
user_tab_columns utc
LEFT JOIN
user_col_comments ucc
ON utc.table_name = ucc.table_name
AND utc.column_name = ucc.column_name
LEFT JOIN
user_tab_comments utab
ON utc.table_name = utab.table_name
ORDER BY
utc.table_name,
utc.column_id;
'''
cursor = connection.cursor()
cursor.execute(stmt)
rows = cursor.fetchall()
# Convert to one long string
result_string = '\n'.join([str(row) for row in rows])
cursor.close()
return result_string
This function queries the Oracle data dictionary to get information about all tables and columns, including any comments. It returns everything as a single string that we can pass to the LLM.
Generating SQL from natural language
Now let’s write the function that takes a natural language question and generates SQL:
def generate_sql(question: str, schema: str, model: str):
prompt = f'''
You are an SQL assistant for Oracle Database.
You create Oracle SQL statements to help answer user questions.
Given the user's question and the schema information, write an SQL
query to answer the question.
Schema:
{schema}
User question:
{question}
Respond with the SQL only. Do not add any extra characters or delimiters.
'''
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0,
)
return response.choices[0].message.content.strip()
This function takes the question, the schema information, and the model to use. It constructs a prompt that gives the LLM the context it needs and asks for just the SQL query.
Executing SQL queries
We need a function to actually run the generated SQL:
def execute_sql(stmt):
cursor = connection.cursor()
cursor.execute(stmt)
rows = cursor.fetchall()
# Convert to one long string
result_string = '\n'.join([str(row) for row in rows])
cursor.close()
return result_string
This executes the query and returns the results as a string.
The reflection step
Here’s where it gets interesting – the function that reviews the SQL and results, and potentially generates improved SQL:
import json
def refine_sql(question, sql_query, output, schema, model):
prompt = f'''
You are a SQL reviewer and refiner.
User asked:
{question}
Original SQL:
{sql_query}
SQL Output:
{output}
Schema:
{schema}
Step 1: Evaluate if the SQL OUTPUT fully answers the user's question.
Step 2: If improvement is needed, provide a refined SQL query for Oracle.
If the original SQL is already correct, return it unchanged.
Return a strict JSON object with two fields:
- "feedback": brief evaluation and suggestions
- "refined_sql": the final SQL to run
Return ONLY the actual JSON document.
Do NOT add any extra characters or delimiters outside of the actual JSON itself.
In particular do NOT include backticks before and after the JSON document.
'''
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0,
)
content = response.choices[0].message.content
try:
obj = json.loads(content)
feedback = str(obj.get("feedback", "")).strip()
refined_sql = str(obj.get("refined_sql", sql_query)).strip()
if not refined_sql:
refined_sql = sql_query
except Exception:
# Fallback if model doesn't return valid JSON
feedback = content.strip()
refined_sql = sql_query
return feedback, refined_sql
This is the heart of the reflection pattern. The function:
Shows the LLM the original question, the generated SQL, and the actual results
Asks it to evaluate whether the SQL output really answers the question
If not, asks for an improved query
Returns both the feedback and the refined SQL as JSON
The JSON format makes it easy to parse the response and extract both pieces of information. I had to be fairly pedantic to get gpt-4o to give me just JSON!
Providing a final answer
Finally, let’s write a function to convert the query results into a natural language answer:
def provide_final_answer(question, output, model):
prompt = f'''
You are helpful assistant.
Given a user's question, and the results of a database query
which has been created, evaluated, improved and executed already
in order to get the provided output, you should provide an
answer to the user's question.
User question:
{question}
Query results:
{output}
'''
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0,
)
return response.choices[0].message.content.strip()
This takes the final query results and turns them into a friendly, natural language response for the user.
Putting it all together
Now let’s create the main function that orchestrates the entire process:
The original SQL query retrieves the top 10 customers based on income, which may not
fully answer the question of 'top customers' as it could be interpreted in terms of
sales or transactions. To better answer the question, we should consider the total
sales or transactions made by each customer.
Great! The LLM recognized that “top customers” probably means customers who spend the most, not customers who earn the most.
Second attempt (SQL V2):
SELECT C.CUST_ID, C.FIRST_NAME, C.LAST_NAME, C.EMAIL, SUM(S.ACTUAL_PRICE) AS TOTAL_SALES
FROM CUSTOMER C
JOIN CUSTSALES S ON C.CUST_ID = S.CUST_ID
GROUP BY C.CUST_ID, C.FIRST_NAME, C.LAST_NAME, C.EMAIL
ORDER BY TOTAL_SALES DESC
FETCH FIRST 10 ROWS ONLY;
Much better! Now it’s joining with the sales data and calculating total spending per customer.
The top customer is Tsubasa Nakajima with $2,356.05 in total sales, followed by Steffi Bielvenstram with $2,334.73, and so on. These are very different customers from the high-income list we got in the first attempt!
Natural language answer:
Our top customers, based on the provided data, are:
1. Tsubasa Nakajima - Email: tsubasa.nakajima2@oraclemail.com, Total: $2356.05
2. Steffi Bielvenstram - Email: steffi.bielvenstram@oraclemail.com, Total: $2334.73
3. Guadalupe Zamora - Email: guadalupe.zamora@oraclemail.com, Total: $2329.76
...
These customers have the highest total amounts associated with them.
What I learned
This reflection approach really does help. The LLM is pretty good at recognizing when its initial SQL doesn’t quite match the intent of the question – especially when it can see the actual results.
The pattern of generate → execute → reflect → regenerate is more expensive (two LLM calls instead of one for generation, plus one more for the final answer), but the quality improvement is noticeable. For production use, you might want to:
Cache schema information instead of fetching it every time
Add more sophisticated error handling for SQL errors
Consider running both queries in parallel and comparing results
Track which types of questions benefit most from reflection
Use the reflection feedback to build a dataset for fine-tuning
The approach is straightforward to implement and the results speak for themselves – the reflection step caught a subtle but important misinterpretation that would have given technically correct but unhelpful results.
Give it a try with your own database and questions – I think you’ll find the reflection step catches a lot of these subtle misinterpretations that would otherwise lead to valid but wrong answers.
What next? I am going to experiment with some more complex questions, and then compare the performance of a number of different LLMs to see how they go with and without reflection. Stay tuned
]]>https://redstack.dev/2025/11/12/using-reflection-to-help-llms-write-better-sql/feed/04244Using Multiple Datasources with Spring Boot and Spring Data JPA
https://redstack.dev/2025/10/30/using-multiple-datasources-with-spring-boot-and-spring-data-jpa/
https://redstack.dev/2025/10/30/using-multiple-datasources-with-spring-boot-and-spring-data-jpa/#respondThu, 30 Oct 2025 22:19:45 +0000https://redstack.dev/?p=4228Continue reading →]]>Hi everyone! Today I want to show you how to configure multiple datasources in a Spring Boot application using Spring Data JPA and the Oracle Spring Boot Starter for Universal Connection Pool (UCP).
This is a pattern you’ll need when you have a single application that needs to connect to multiple databases. Maybe you have different domains in separate databases, or you’re working with legacy systems, or you need to separate read and write operations across different database instances. Whatever the reason, Spring Boot makes this pretty straightforward once you understand the configuration pattern.
For this example, we’re going to build a simple application that manages two separate domains:
Customers – stored in one database
Products – stored in a different database
Each domain will have its own datasource, entity manager, and transaction manager. We’ll use Spring Data JPA repositories to interact with each database, and we’ll show how to use both datasources in a REST controller.
I am assuming you have a database with two users called customer and product and some tables. Here’s the SQL to set that up:
$ sqlplus sys/Welcome12345@localhost:1521/FREEPDB1 as sysdba
alter session set container=freepdb1;
create user customer identified by Welcome12345;
create user product identified by Welcome12345;
grant connect, resource, unlimited tablespace to customer;
grant connect, resource, unlimited tablespace to product;
commit;
$ sqlplus customer/Welcome12345@localhost:1521/FREEPDB1
create table customer (id number, name varchar2(64));
insert into customer (id, name) values (1, 'mark');
commit;
$ sqlplus product/Welcome12345@localhost:1521/FREEPDB1
create table product (id number, name varchar2(64));
insert into product (id, name) values (1, 'coffee machine');
commit;
Step 1: Dependencies
Let’s start with the Maven dependencies. Here’s what you’ll need in your pom.xml:
<dependencies>
<!-- Spring Boot Starter Web for REST endpoints -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Oracle Spring Boot Starter for UCP -->
<dependency>
<groupId>com.oracle.database.spring</groupId>
<artifactId>oracle-spring-boot-starter-ucp</artifactId>
<version>25.3.0</version>
</dependency>
</dependencies>
The key dependency here is the oracle-spring-boot-starter-ucp, which provides autoconfiguration for Oracle’s Universal Connection Pool. UCP is Oracle’s high-performance connection pool implementation that provides features like connection affinity, Fast Connection Failover, and Runtime Connection Load Balancing.
Step 2: Configure the Datasources in application.yaml
Now let’s configure our two datasources in the application.yaml file. We’ll define connection properties for both the customer and product databases:
Notice that we’re using custom property prefixes (spring.datasource.customer and product) instead of the default spring.datasource. This is because Spring Boot’s autoconfiguration will only create a single datasource by default. When you need multiple datasources, you need to create them manually and use custom configuration properties.
In this example, both datasources happen to point to the same database server but use different schemas (users). In a real-world scenario, these would typically point to completely different database instances.
Step 3: Configure the Customer Datasource
Now we need to create the configuration classes that will set up our datasources, entity managers, and transaction managers. Let’s start with the customer datasource.
Create a new package called customer and add a configuration class called CustomerDataSourceConfig.java:
package com.example.demo.customer;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "customerEntityManagerFactory", transactionManagerRef = "customerTransactionManager", basePackages = {
"com.example.demo.customer" })
public class CustomerDataSourceConfig {
@Bean(name = "customerProperties")
@ConfigurationProperties("spring.datasource.customer")
public DataSourceProperties customerDataSourceProperties() {
return new DataSourceProperties();
}
/**
* Creates and configures the customer DataSource.
*
* @param properties the customer datasource properties
* @return configured DataSource instance
*/
@Primary
@Bean(name = "customerDataSource")
@ConfigurationProperties(prefix = "spring.datasource.customer")
public DataSource customerDataSource(@Qualifier("customerProperties") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().build();
}
/**
* Reads customer JPA properties from application.yaml.
*
* @return Map of JPA properties
*/
@Bean(name = "customerJpaProperties")
@ConfigurationProperties("spring.jpa.customer.properties")
public java.util.Map<String, String> customerJpaProperties() {
return new java.util.HashMap<>();
}
/**
* Creates and configures the customer EntityManagerFactory.
*
* @param builder the EntityManagerFactoryBuilder
* @param dataSource the customer datasource
* @param jpaProperties the JPA properties from application.yaml
* @return configured LocalContainerEntityManagerFactoryBean
*/
@Primary
@Bean(name = "customerEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean customerEntityManagerFactory(EntityManagerFactoryBuilder builder,
@Qualifier("customerDataSource") DataSource dataSource,
@Qualifier("customerJpaProperties") java.util.Map<String, String> jpaProperties) {
return builder.dataSource(dataSource)
.packages("com.example.demo.customer")
.persistenceUnit("customers")
.properties(jpaProperties)
.build();
}
@Bean
@ConfigurationProperties("spring.jpa.customer")
public PlatformTransactionManager customerTransactionManager(
@Qualifier("customerEntityManagerFactory") LocalContainerEntityManagerFactoryBean entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory.getObject());
}
}
Let’s break down what’s happening here:
@EnableJpaRepositories – This tells Spring Data JPA where to find the repositories for this datasource. We specify the base package (com.example.multidatasource.customer), and we reference the entity manager factory and transaction manager beans by name.
@Primary – We mark the customer datasource as the primary one. This means it will be used by default when autowiring a datasource, entity manager, or transaction manager without a @Qualifier. You must have exactly one primary datasource when using multiple datasources.
customerDataSource() – This creates the datasource bean using Spring Boot’s DataSourceBuilder. The @ConfigurationProperties annotation binds the properties from our application.yaml (with the customer.datasource prefix) to the datasource configuration.
customerEntityManagerFactory() – This creates the JPA entity manager factory, which is responsible for creating entity managers. We configure it to scan for entities in the customer package and set up Hibernate properties.
customerTransactionManager() – This creates the transaction manager for the customer datasource. The transaction manager handles transaction boundaries and ensures ACID properties.
Step 4: Configure the Product Datasource
Now let’s create the configuration for the product datasource. Create a new package called product and add ProductDataSourceConfig.java:
package com.example.demo.product;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "productEntityManagerFactory", transactionManagerRef = "productTransactionManager", basePackages = {
"com.example.demo.product" })
public class ProductDataSourceConfig {
@Bean(name = "productProperties")
@ConfigurationProperties("spring.datasource.product")
public DataSourceProperties productDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "productDataSource")
@ConfigurationProperties(prefix = "spring.datasource.product")
public DataSource productDataSource(@Qualifier("productProperties") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().build();
}
/**
* Reads product JPA properties from application.yaml.
*
* @return Map of JPA properties
*/
@Bean(name = "productJpaProperties")
@ConfigurationProperties("spring.jpa.product.properties")
public java.util.Map<String, String> productJpaProperties() {
return new java.util.HashMap<>();
}
/**
* Creates and configures the product EntityManagerFactory.
*
* @param builder the EntityManagerFactoryBuilder
* @param dataSource the product datasource
* @param jpaProperties the JPA properties from application.yaml
* @return configured LocalContainerEntityManagerFactoryBean
*/
@Bean(name = "productEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean productEntityManagerFactory(@Autowired EntityManagerFactoryBuilder builder,
@Qualifier("productDataSource") DataSource dataSource,
@Qualifier("productJpaProperties") java.util.Map<String, String> jpaProperties) {
return builder.dataSource(dataSource)
.packages("com.example.demo.product")
.persistenceUnit("products")
.properties(jpaProperties)
.build();
}
@Bean
@ConfigurationProperties("spring.jpa.product")
public PlatformTransactionManager productTransactionManager(
@Qualifier("productEntityManagerFactory") LocalContainerEntityManagerFactoryBean entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory.getObject());
}
}
The product configuration is almost identical to the customer configuration, with a few key differences:
No @Primary annotations – Since we already designated the customer datasource as primary, we don’t mark the product beans as primary.
Different package – The @EnableJpaRepositories points to the product package, and the entity manager factory scans the product package for entities.
Different bean names – All the beans have different names (productDataSource, productEntityManagerFactory, productTransactionManager) to avoid conflicts.
Step 5: Create the Domain Models
Now let’s create the JPA entities for each datasource. First, in the customer package, create Customer.java:
package com.example.demo.customer;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Customer {
@Id
public int id;
public String name;
public Customer() {
this.id = 0;
this.name = "";
}
}
And in the product package, create Product.java:
package com.example.demo.product;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Product {
@Id
public int id;
public String name;
public Product() {
this.id = 0;
this.name = "";
}
}
Step 6: Create the Repositories
Now let’s create Spring Data JPA repositories for each entity. In the customer package, create CustomerRepository.java:
Finally, let’s create a REST controller that demonstrates how to use both datasources. Create a controller package and add CustomerController.java:
package com.example.demo.controllers;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.customer.Customer;
import com.example.demo.customer.CustomerRepository;
@RestController
public class CustomerController {
final CustomerRepository customerRepository;
public CustomerController(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@GetMapping("/customers")
public List<Customer> getCustomers() {
return customerRepository.findAll();
}
}
A few important things to note about the controller:
Transaction Managers – When you have multiple datasources, you need to explicitly specify which transaction manager to use. Notice the @Transactional("customerTransactionManager") and @Transactional("productTransactionManager") annotations on the write operations. If you don’t specify a transaction manager, Spring will use the primary one (customer) by default.
Repository Autowiring – The repositories are autowired normally. Spring knows which datasource each repository uses based on the package they’re in, which we configured in our datasource configuration classes.
Cross-datasource Operations – The initializeData() method demonstrates working with both datasources in a single method. However, note that these operations are not in a distributed transaction – if one fails, the other won’t automatically roll back. If you need distributed transactions across multiple databases, you would need to use JTA (Java Transaction API).
Let’s also create ProductController.java:
package com.example.demo.controllers;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.product.Product;
import com.example.demo.product.ProductRepository;
@RestController
public class ProductController {
final ProductRepository productRepository;
public ProductController(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@GetMapping("/products")
public List<Product> getProducts() {
return productRepository.findAll();
}
}
Testing the Application
Now you can run your application! Make sure you have two Oracle database users created (customer and product), or adjust the configuration to point to your specific databases.
Start the application:
mvn spring-boot:run
Then you can test it with some curl commands:
# Get all customers
$ curl http://localhost:8080/customers
[{"id":1,"name":"mark"}]
# Get all products
$ curl http://localhost:8080/products
[{"id":1,"name":"coffee machine"}]
Wrapping Up
And there you have it! We’ve successfully configured a Spring Boot application with multiple datasources using Spring Data JPA and Oracle’s Universal Connection Pool. The key points to remember are:
Custom configuration properties – Use custom prefixes for each datasource in your application.yaml
Manual configuration – Create configuration classes for each datasource with beans for the datasource, entity manager factory, and transaction manager
Primary datasource – Designate one datasource as primary using @Primary
Package organization – Keep entities and repositories for each datasource in separate packages
Explicit transaction managers – Specify which transaction manager to use for write operations with @Transactional
This pattern works great when you need to connect to multiple databases, whether they’re different types of databases or different instances of the same database. Oracle’s Universal Connection Pool provides excellent performance and reliability for your database connections.
]]>https://redstack.dev/2025/10/30/using-multiple-datasources-with-spring-boot-and-spring-data-jpa/feed/04228Custom vector distance functions in Oracle (using JavaScript)
https://redstack.dev/2025/10/20/custom-vector-distance-functions-and-hybrid-vector-search-in-oracle-using-javascript/
https://redstack.dev/2025/10/20/custom-vector-distance-functions-and-hybrid-vector-search-in-oracle-using-javascript/#respondMon, 20 Oct 2025 16:00:42 +0000https://redstack.dev/?p=4188Continue reading →]]>In case you missed it, Oracle Database 26ai was announced last week at Oracle AI World, with a heap of new AI features and capabilities like hybrid vector search, MCP server support, acceleration with NVIDIA and much more – check the link for details.
Of course, I wanted to check it out, and I was thinking about what to do first. I remembered this LinkedIn post from Anders Swanson about implementing custom vector distance functions in Oracle using the new JavaScript capabilities, and I thought that could be something interesting to do, so I am going to show you how to implement and use Jaccard distance for dense vector embeddings for similarity searches.
Now, this is a slightly contrived example, because I am more interested in showing you how to add a custom metric than in the actual metric itself. I chose Jaccard because the actual implementation is pretty compact.
Now, Oracle does already include Jaccard distance, but only for the BINARY data type, which is where Jaccard is mostly used. But there is a version that can be used for continuous/real-valued vectors as well (this version is for dense vectors), and that is what we will implement.
This is the formula for Jaccard similarity for continuous vectors. This is also known as the Tanimoto coefficient. It is the intersection divided by the union (or zero if the union is zero):
To get the Jaccard distance, we just subtract the Jaccard similarity from one.
Before we start, let’s look at a two-dimensional example to get a feel for how it works. Of course, the real vectors created by embedding models have many more dimensions, but it is hard for us to visualize more than two or three dimensions without also introducing techniques like dimensionality reduction and projection).
Here we have two vectors A [5 8] and B [7 4]:
The union is calculated using the max values, as you see in the formular above, so in this example it is 7×8, as shown by the area shaded pink. The intersection is calculated with the min values, so it is 5×4, as shown by the green area.
So in this example, the Jaccard similarity is (7×8) / (5×4) = 56 / 20 = 0.6
And so the Jaccard distance is 1 – 0.6 = 0.4
Ok, now that we have some intuition about how this distance metric works, let’s implement it in Oracle.
Start up an Oracle Database
First, let’s fire up Oracle Database Free 26ai in a container:
This will pull the latest image, which at the time of writing is 26ai (version tag 23.26.0.0). You can check the logs to see when startup is complete, you’ll see a message “DATABASE IS READY TO USE”:
docker logs -f db26ai
Let’s create a user called vector with the necessary privileges:
docker exec -i db26ai sqlplus sys/Welcome12345@localhost:1521/FREEPDB1 as sysdba <<EOF
alter session set container=FREEPDB1;
create user vector identified by vector;
grant connect, resource, unlimited tablespace, create credential, create procedure, create mle, create any index to vector;
commit;
EOF
Now you can connect with your favorite client. I am going to use Oracle SQL Developer for VS Code. See the link for install instructions.
Implement the custom distance function
Open up an SQL Worksheet, or run this in your tool of choice:
create or replace function jaccard_distance("a" vector, "b" vector)
return binary_double
deterministic parallel_enable
as mle language javascript pure {{
// check the vectors are the same length
if (a.length !== b.length) {
throw new Error('Vectors must have same length');
}
let intersection = 0;
let union = 0;
for (let i = 0; i < a.length; i++) {
intersection += Math.min(a[i], b[i]);
union += Math.max(a[i], b[i]);
}
// handle the case where union is zero (all-zero vectors)
if (union === 0) {
return 0;
}
const similarity = intersection / union;
return 1 - similarity;
}};
/
Let’s walk throught this. First, you see that we are creating a function called jaccard_distance which accepts two vectors (a and b) as input and returns a binary_double. This function sugnature is required for distance functions. Next we must include the deterministric keyword and we have also included the parallel_enable keyword so that this function could be used with HNSW vector indexes. For the purposes of this example, you can just ignore those or assume that they are just needed as part of the function signature.
Next you see that we mention this will be an MLE function written in JavaScript, and we added the pure keyword to let the database know that this is a pure function – meaning it has no side effects, it will not update any data, and its output will always be the same for a given set of inputs (i.e., that it is memoizable).
Then we have the actual implementation of the function. First, we check that the vectors have the same length (i.e., the same number of dimensions) which is required for this calculation to be applicable.
Then we work through the vectors and collect the minimums and maximums to calculate the intersection and the union.
Next, we check if the union is zero, and if so we return zero to handle that special case. And finally, we calculate the similarity, then subtract it from one to get the distance and return that.
Using our custom distance function
Great, so let’s test our function. We can start by creating a table t1 to store some vectors:
create table t1 (
id number,
v vector(2, float32)
);
And let’s add a couple of vectors, including the one we saw in the example above [5 8]:
Create a new Jupyter Notebook using File > New File… then choose Jupyter Notebook as the type of file, and save your new file at jaccard.ipynb.
First, we need to set up the Python runtime environment. Click on the Select Kernel button (its on the top right). Select Python Environment then Create Python Environment. Select the option to create a Venv (Virtual Environment) and choose your Python interpreter. I recommend using at least Python 3.11. This will download all the necessary files and will take a minute or two.
Now, let’s install the libraries we will need – enter this into a cell and run it:
%pip install oracledb sentence-transformers
Now, connect to the same Oracle database (again, enter this into a cell and run it):
Let’s create a table to hold 1024 dimension vectors that we will create with the mxbai-embed-large-v1 embedding model. Back in your SQL Worksheet, run this statement:
create table t2 (
id number,
v vector(1024, float32)
);
Ok, now let’s create some embeddings. Back in your notebook, create a new cell with this code:
import oracledb
from sentence_transformers import SentenceTransformer
# Initialize the embedding model
print("Loading embedding model...")
model = SentenceTransformer('mixedbread-ai/mxbai-embed-large-v1')
# Your text data
texts = [
"The quick brown fox jumps over the lazy dog",
"Machine learning is a subset of artificial intelligence",
"Oracle Database 23ai supports vector embeddings",
"Python is a popular programming language",
"Embeddings capture semantic meaning of text"
]
# Generate embeddings
print("Generating embeddings...")
embeddings = model.encode(texts)
Let’s discuss what we are doing in this code. First, we are going to download the embedding model usign the SentenceTransformer. Then, we define a few simple texts that we can use for this example and use the embedding model to create the vector embeddings for those texts.
If you want to see what the embeddings look like, just enter “embeddings” in a cell and run it. In the output you can see the shape is 5 (rows) with 1024 dimensions and the type is float32.
Now, let’s insert the embeddings into our new table t2:
import array
cursor = connection.cursor()
# Insert data
for i in range(len(embeddings)):
cursor.execute("""
INSERT INTO t2 (id, v)
VALUES (:1, :2)
""", [i, array.array('f', embeddings[i].tolist())])
connection.commit()
print(f"Successfully inserted {len(texts)} records")
You can take a look at the vectors using the simple query (back in your SQL Worksheet):
select * from t2
Which will show you something like this:
And, now let’s try our distance function with these vectors. Back in your notebook, run this cell. I’ve included the built-in cosine distance as well, just for comparison purposes:
query = array.array('f', model.encode("Antarctica is the driest continent").tolist())
cursor = connection.cursor()
cursor.execute("""
select
id,
jaccard_distance(v, :1),
vector_distance(v, :2, cosine)
from t2
order by id
""", [query, query])
for row in cursor:
print(f"id: {row[0]} has jaccard distance: {row[1]} and cosine distance: {row[2]}")
cursor.close()
Your output will look something like this:
id: 0 has jaccard distance: 2.0163214889484307 and cosine distance: 0.7859490566650003
id: 1 has jaccard distance: 2.0118706751976925 and cosine distance: 0.6952327173906239
id: 2 has jaccard distance: 2.0152858933816775 and cosine distance: 0.717824211314015
id: 3 has jaccard distance: 2.0216149035530537 and cosine distance: 0.6455277387099003
id: 4 has jaccard distance: 2.0132575761281766 and cosine distance: 0.6962028121886988
Well, there you go! We implemented and used a custom vector distance function. Enjoy!
]]>https://redstack.dev/2025/10/20/custom-vector-distance-functions-and-hybrid-vector-search-in-oracle-using-javascript/feed/04188Let’s make a simple MCP tool for Oracle AI Vector Search
https://redstack.dev/2025/10/08/lets-make-a-simple-mcp-tool-for-oracle-ai-vector-search/
https://redstack.dev/2025/10/08/lets-make-a-simple-mcp-tool-for-oracle-ai-vector-search/#commentsWed, 08 Oct 2025 20:02:10 +0000https://redstack.dev/?p=4164Continue reading →]]>In this earlier post, we created a vector store in our Oracle Database 23ai and populated it with some content from Moby Dick. Since MCP is very popular these days, I thought it might be interesting to look how to create a very simple MCP server to expose the similarity search as and MCP tool.
Let’s jump right into it. First we are going to need a requirements.txt file with a list of the dependencies we need:
Note: I used Python 3.12 and a virtual environment.
Now let’s create a file called mcp_server.py and get to work! Let’s start with some imports:
import asyncio
import oracledb
from mcp.server import Server
from mcp.types import Tool, TextContent
from pydantic import BaseModel
from langchain_community.vectorstores import OracleVS
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain_huggingface import HuggingFaceEmbeddings
And we are going to need the details of the database so we can connect to that, so let’s define some variables to hold those parameters:
# Database connection parameters for Oracle Vector Store
DB_USERNAME = "vector"
DB_PASSWORD = "vector"
DB_DSN = "localhost:1521/FREEPDB1"
TABLE_NAME = "moby_dick_500_30"
Note: These match the database and vector store used in the previous post.
Let’s create a function to connect to the database, and set up the embedding model and the vector store.
# Global variables for database connection and embedding model
# These are initialized once on server startup for efficiency
embedding_model = None # HuggingFace sentence transformer model
vector_store = None # LangChain OracleVS wrapper for vector operations
connection = None # Oracle database connection
def initialize_db():
"""
Initialize database connection and vector store
This function is called once at server startup to establish:
1. Connection to Oracle database
2. HuggingFace embedding model (sentence-transformers/all-mpnet-base-v2)
3. LangChain OracleVS wrapper for vector similarity operations
The embedding model converts text queries into 768-dimensional vectors
that can be compared against pre-computed embeddings in the database.
"""
global embedding_model, vector_store, connection
# Connect to Oracle database using oracledb driver
connection = oracledb.connect(
user=DB_USERNAME,
password=DB_PASSWORD,
dsn=DB_DSN
)
# Initialize HuggingFace embeddings model
# This model converts text to 768-dimensional vectors
# Same model used to create the original embeddings in the database
embedding_model = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-mpnet-base-v2"
)
# Initialize vector store wrapper
# OracleVS provides convenient interface for vector similarity operations
vector_store = OracleVS(
client=connection,
table_name=TABLE_NAME,
embedding_function=embedding_model,
# Use cosine similarity for comparison
distance_strategy=DistanceStrategy.COSINE,
)
Again, note that I am using the same embedding model that we used to create the vectors in this vector store. This is important because we need to create embedding vectors for the queries using the same model, so that similarity comparisons will be valid. It’s also important that we use the right distance strategy – for text data, cosine is generally agreed to be the best option. For performance reasons, if we had created a vector index, we’d want to use the same algorithm so the index would be used when performing the search. Oracle will default to doing an “exact search” if there is no index and the algorithm does not match.
Now, let’s add a function to perform a query in our Moby Dick vector store, we’ll include a top-k parameter so the caller can specify how many results they want:
def search_moby_dick(query: str, k: int = 4) -> list[dict]:
"""
Perform vector similarity search on the moby_dick_500_30 table
This function:
1. Converts the query text to a vector using the embedding model
2. Searches the database for the k most similar text chunks
3. Returns results ranked by similarity (cosine distance)
Args:
query: The search query text (natural language)
k: Number of results to return (default: 4)
Returns:
List of dictionaries containing rank, content, and metadata for each result
"""
if vector_store is None:
raise RuntimeError("Vector store not initialized")
# Perform similarity search
# The query is automatically embedded and compared against database vectors
docs = vector_store.similarity_search(query, k=k)
# Format results into structured dictionaries
results = []
for i, doc in enumerate(docs):
results.append({
"rank": i + 1, # 1-indexed ranking by similarity
"content": doc.page_content, # The actual text chunk
"metadata": doc.metadata # Headers from the original HTML structure
})
return results
As you can see, this function returns a dictionary containing the rank, the content (chunk) and the metadata.
Ok, now let’s turn this into an MCP server! First let’s create the server instance:
# Create MCP server instance
# The server name "moby-dick-search" identifies this server in MCP client connections
app = Server("moby-dick-search")
Now we want to provide a list-tools method so that MCP clients can find out what kinds of tools this server provides. We are just going to have our search tool, so let’s define that:
@app.list_tools()
async def list_tools() -> list[Tool]:
"""
MCP protocol handler: returns list of available tools
Called by MCP clients to discover what capabilities this server provides.
This server exposes a single tool: search_moby_dick
Returns:
List of Tool objects with names, descriptions, and input schemas
"""
return [
Tool(
name="search_moby_dick",
description="Search the Moby Dick text using vector similarity. Returns relevant passages based on semantic similarity to the query.",
inputSchema={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query text"
},
"k": {
"type": "integer",
"description": "Number of results to return (default: 4)",
"default": 4
}
},
"required": ["query"]
}
)
]
And now, the part we’ve all been waiting for – let’s define the actual search tool (and a class to hold the arguments)!
class SearchArgs(BaseModel):
"""
Arguments for the vector search tool
Attributes:
query: The natural language search query
k: Number of most similar results to return (default: 4)
"""
query: str
k: int = 4
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
"""
MCP protocol handler: executes tool calls
Called when an MCP client wants to use one of the server's tools.
Validates the tool name, parses arguments, performs the search,
and returns formatted results.
Args:
name: Name of the tool to call
arguments: Dictionary of tool arguments
Returns:
List of TextContent objects containing the formatted search results
"""
# Validate tool name
if name != "search_moby_dick":
raise ValueError(f"Unknown tool: {name}")
# Parse and validate arguments using Pydantic model
args = SearchArgs(**arguments)
# Perform the vector similarity search
results = search_moby_dick(args.query, args.k)
# Format response as human-readable text
response_text = f"Found {len(results)} results for query: '{args.query}'\n\n"
for result in results:
response_text += f"--- Result {result['rank']} ---\n"
response_text += f"Metadata: {result['metadata']}\n"
response_text += f"Content: {result['content']}\n\n"
# Return as MCP TextContent type
return [TextContent(type="text", text=response_text)]
That was not too bad. Finally, let’s set up a main function to start up everything and handle the requests:
async def main():
"""
Main entry point for the MCP server
This function:
1. Initializes the database connection and embedding model
2. Sets up stdio transport for MCP communication
3. Runs the server event loop to handle requests
The server communicates via stdio (stdin/stdout), which allows
it to be easily spawned by MCP clients as a subprocess.
"""
# Initialize database connection and models
initialize_db()
# Import stdio server transport
from mcp.server.stdio import stdio_server
# Run the server using stdio transport
# The server reads MCP protocol messages from stdin and writes responses to stdout
async with stdio_server() as (read_stream, write_stream):
await app.run(
read_stream,
write_stream,
app.create_initialization_options()
)
if __name__ == "__main__":
asyncio.run(main())
Ok, that’s it! We can run this with the command:
python mcp_server.py
Now, to test it, we’re groing to need a client! MCP Inspector is the logical place to start, you can get it from here, or (assuming you have node installed) by just running this command:
That’s going to start up a UI that looks like this:
Click on the connect button, and you should see an updated screen in a few seconds that looks like this:
Go ahead and click on List Tools and you will see our Search Moby Dick Tool show up – click on it to try it out.
You should see some results like this:
There you go, it works great! And that’s a super simple, basic MCP server and tool! Enjoy.
]]>https://redstack.dev/2025/10/08/lets-make-a-simple-mcp-tool-for-oracle-ai-vector-search/feed/14164Exploring securing vector similarity searches with Real Application Security
https://redstack.dev/2025/10/08/exploring-securing-vector-similarity-searches-with-real-application-security/
https://redstack.dev/2025/10/08/exploring-securing-vector-similarity-searches-with-real-application-security/#respondWed, 08 Oct 2025 17:04:40 +0000https://redstack.dev/?p=4018Continue reading →]]>In this post, I want to explore how you can use Real Application Security to provide access controls for vectors in a vector store in Oracle Database 23ai.
I’m going to use the vector store we created in the last post as an example. If you want to follow along, you should follow that one first to create and populate your vector store, then come back here.
You should have a vector store table called MOBY_DICK_500_30 that you created in that previous post. You can connect to Oracle using SQLcl or SQL*Plus or whatever tool you prefer and check the structure of that table:
SQL> describe moby_dick_500_30
Name Null? Type
____________ ___________ ____________________________
ID NOT NULL RAW(16 BYTE)
TEXT CLOB
METADATA JSON
EMBEDDING VECTOR(768,FLOAT32,DENSE)
Let’s observe that that metadata column contains the document structure information from the loaders that we used. If we filter for Chapter 12, we can see there are 13 vectors associated with that chapter:
SQL> select metadata from moby_dick_500_30 where metadata like '%CHAPTER 12.%';
METADATA
__________________________________________________________________________________
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
{"Header 1":"MOBY-DICK; or, THE WHALE.","Header 2":"CHAPTER 12. Biographical."}
13 rows selected.
We are going to use this metadata to filter access to the vectors.
Set up permissions
Let’s start by setting up the necessary permissions. You will need to run this as the SYS user:
alter session set container=freepdb1;
grant create session, xs_session_admin to vector;
exec sys.xs_admin_util.grant_system_privilege('provision', 'vector', sys.xs_admin_util.ptype_db);
grant create role to vector;
exec sys.xs_admin_util.grant_system_privilege('admin_sec_policy', 'vector', sys.xs_admin_util.ptype_db);
exec sys.xs_admin_util.grant_system_privilege('ADMIN_ANY_SEC_POLICY', 'vector', sys.xs_admin_util.ptype_db);
Great! Now let’s set up Real Application Security. We will run the rest of these commands as the VECTOR user.
So there you have it! We can define policies to easily control access to vectors. In this example we used the metadata to create the filtering rules, of course you could create whatever kind of rules you need.
This allows you to have a vector store which can be easily filtered for different users (or roles), essentially creating a virtual private vector store. You might want to allow ‘customer-support’ role access a certain subset of vectors for example, but your ‘supervisor’ role to access a larger set (or all) of the vectors.
What’s great about this, is that the security is enforced in the database itself. When an AI Assistant, chatbot, MCP client, etc., performs a vector search, they will only ever be able to get back results from the vectors that the user is allowed to see. The database will never send vectors to users which they are not allowed to see. So you don’t have to worry about trusting the LLM not to make a mistake and give out the wrong data, because it will literally never see the data in the first place.
]]>https://redstack.dev/2025/10/08/exploring-securing-vector-similarity-searches-with-real-application-security/feed/04018Basic Retrieval Augmented Generation with Oracle Vector Store in LangChain
https://redstack.dev/2025/05/23/basic-retrieval-augmented-generation-with-oracle-vector-store-in-langchain/
https://redstack.dev/2025/05/23/basic-retrieval-augmented-generation-with-oracle-vector-store-in-langchain/#commentsFri, 23 May 2025 23:29:15 +0000https://redstack.dev/?p=4082Continue reading →]]>In this earlier post, we learned how to create a Vector Store in Oracle from LangChain, the hugely popular Python library for working with Generative AI and Large Language Models. We populated it with a little data and then performed some simple vector similarity searches.
In this post, let’s expand on that to implement basic Retrieval Augmented Generation!
First, let’s talk about some concepts – if you alread know this, feel free to jump ahead!
Generative AI – This is a type of Artificial Intelligence (AI) that uses a specialized form of machine learning model, called a Large Language Model (or “LLM”), to create (“generate”) new content based on a prompt from a user. It works by looking at the “tokens” that it received in the input (the “prompt”) and then figuring out what is the most probable next token in the sequence. What is a token? Well, it may be a word, or a part of a word, but we use the word “token” because it could also be part of an audio file or an image, since some of these models support other types of data, not just text. Note that it only generates one token at a time – you have to “run” the model again for every subsequent token.
Training – these models are “trained” by exposing them to very large amounts of data. Usually the data is publicly available information, collected from the Internet and/or other repositories. Training a model is very expensive, both in terms of time, and in terms of the cost of running the specialized GPU hardware needed to perform the training. You may see a model described as having “70 billion parameters” or something like that. Training is basically a process of tuning the probabilities of each of these parameters based on the new input.
When a model sees a prompt like “My Husky is a very good” it will use those probabilities to determine that comes next. In this example, “dog” would have a very high probability of being the next “token”.
Hyper-parameters – models also have extra parameters that control how they behave. These so-called “hyper-parameters” include things like “temperature” which controls how creative the model will be, “top-K” which controls how many options the model will consider when choose the next token, and various kinds of “frequency penalties” that will cause the model to be more or less likely to reuse/repeat tokens. Of course these are just a few examples.
Knowledge cut-off – an important property of LLMs is that they have not been exposed to any information that was created after their training ended. So a model training in 2023 would not know who won an election held in 2024 for example.
Hallucination – LLMs tend to “make up an answer” if they do not “know” the answer. Now, obviously they don’t really know anything in the same sense that we know things, they are rworking with probabilities. But if we can anthropomorphize them for a moment, they tend to “want” to be helpful, and they are very likely to offer you a very confident but completely incorrect answer if they do not have the necessary information to answer a question.
Now, of course a lot of people want to use this exciting new technology to implement solutions to help their customers or users. ChatBots is a prime example of something that is frequently implemented using Generative AI these days. But, of course no new technology is a silver bullet, and they all come with their own challenges and issues. Let’s consider some common challenges when attempting to implement a project with Generative AI:
Which model to use? There are many models available, and they have all beeen trained differently. Some are specialized models that are trained to perform a particular task, for example summarizing a document. Other models are general purpose and can perform different tasks. Some models understand only one language (like English) and others understand many. Some models only understand text, others only images, others video, and others still are multi-modal and understand various different types of data. Models also have different licensing requirements. Some models are provided as a service, like a utility, where you typically pay some very small amount per request. Other models are able to be self-hosted, or run on your own hardware.
Privacy. Very often the data that you need for your project is non-public data, and very often you do not want to share that data with a third-party organization for privacy reasons, or even regulatory reasons, depending on your industry. People are also very wary about a third-party organization using their non-public data to train future models.
How to “tune” to models hyper-parameters. As we discussed earlier, the hyper-parameters control how the model behaves. The settings of these parameters can have a significant impact on the quality of the results that are produced.
Dealing with knowledge cut-off. Giving the model access to information that is newer than when it was trained is also a key challenge. Probably the most obvious way to do this is to continue to model’s training by exposing it to this newer information. This is known as “fine-tuning”. The key challenge is that is an extremely expensive enterprise, requiring specialized GPU hardware and very highly skilled people to plan and run the training.
Enter “Retrieval Augmented Generation,” (or “RAG”) first introduced by Patrick Lewis et al, from Meta, in the 2020 paper “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks“. RAG is a technique that gives LLMs access to non-public information and/or information created after their training and is orders of magnitude less expensive than fine-tuning.
The essence of RAG is to provide the LLM with the information that it needs to answer a question by “stuffing” that information into the LLM’s “context window” or “prompt” along with the actual question. It’s a bit like an open-book test. Imagine you get a question like this:
How much does a checking account from (some bank) cost?
And let’s assume that information is not readily available on the Internet. How would you come up with the answer? You likely could not.
But if the question was more like this:
How much does a checking acount from (some bank) cost?
To answer this question, consult these DOCUMENTS:
(here there would be the actual content of those documents that provide the information necessary to answer that question)
Much easier right? That’s basically what RAG is. It provides the most relevant information to the LLM so that it can answer the question.
So now, the obvious questions are – where does it get this information from, and how does it know which parts are the most relevant?
This is where our Vector Store comes in!
The set of information, the non-public data that we want the LLM to use, we call that the “corpus”. Very often the corpus will be so large that there is no reasonable way for us to just give the LLM the whole thing. Now, as I am writing this in May 2025, there are models that have very large “context windows” and could be given a large amount of data. Llama 4 was just released, as I write this, and has a context window size of 10 million tokens! So you could in fact give it a large amount of information. But models that were released as recently as six or twelve months ago have much smaller context windows.
So the approach we use is to take the corpus, and split it up into small pieces, called “chunks” and we create an “embedding vector” for each of these chunks. This vector is basically an n-dimensional numerical representation of the semantic meaning of the chunk. Chunks with similar meanings will have similiar (i.e., close) vectors. Chunks with different meanings will have vectors that are futher apart.
Now, visualizing an n-dimensional vector is challenging. But if n=2, its a lot easier. So let’s do that! Remember, in real models, n is much more likely to be in the thousands or tens of thousands, but the concepts are the same. Consider the diagram below:
In this diagram, we have only two dimensions, the vertical dimension is “largeness” – how large (or small) the thing is. The horizontal dimension is “dog-ness” – how much the thing is (or is not) a dog.
Notice that both the Saint Bernard and the German Shephard (I hope I got those breeds right!) are large dogs. So the vector for both of them are high on both axes, and their vectors are very close together, because in this two-dimensional world, they are indeed very, very similar. The wolf is also large, but it is not actually a dog. Dogs are related to (descended from) wolves, so it is somewhat dog-like, but its vector is quite a distance away from the actual large dogs.
Now, look at the tennis ball! It is not large, and it is not a dog, so it’s vector is almost in the complete opposite direction to the large dogs.
Now, consider the question “Is a Husky a large dog?”
What we do in RAG, is we take that question, and turn that into a vector, using the exact same “embedding model” that we used to create those vectors we just looked at above, and then we see what other vectors are close to it.
Notice that the resulting vector, represented by the red dot, ended up very close to those two large dogs! So if we did a similarity search, that is, if we found the closest vectors to our question vector, what we would get back is the vectors for the Saint Bernard and the German Shephard.
Here’s a diagram of the RAG process:
So we take the question from the user, we turn it into a vector, we find the closest vectors to that in our corprus, and then we get the actual content that those vectors was created from and give that information to the LLM to allow it to answer the question. Remember, in real life there are many more dimensions, and they are not going to be some concept that we can neatly label, like “largeness”. The actual dimensions are things that are learned by the model over many billions of iterations of weight adjustments as it was exposed to vast amounts of data. The closest (non-mathematical) analogy I can think of is Isaac Asimov’s “positronic brain” in his Robots, Empire and Foundation series which he described as learning through countless small adjustments of uncountable numbers of weights..
Wow! That was a lot of theory! Let’s get back to some code, please!
In the previous post, we populated our vector store with just three very small quotes from Moby Dick. Now, let’s use the entire text!
Let’s create a new notebook. If you followed along in the previous post, you can just create a new notebook in the same project and choose the same environment/kernel. If not, create a new project, then create a notebook, for example basic-rag.ipynb and create a kernel:
Click on the Select Kernel button (its on the top right). Select Python Environment then Create Python Environment. Select the option to create a Venv (Virtual Environment) and choose your Python interpreter. I recommend using at least Python 3.11. This will download all the necessary files and will take a minute or two.
If you created a new environment, install the necessary packages by creating and running a cell with this content. Note that you can run this even if you have a pre-existing environment, it won’t do any harm:
Now, create and run this cell to set your OpenAI API key:
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain.chat_models import init_chat_model
model = init_chat_model("gpt-4o-mini", model_provider="openai")
model.invoke("Hello, world!")
Paste your key in when prompted (see the previous post if you need to know how to get one) and confirm you got the expected response from the model.
Now, let’s connect to the database by creating and running this cell (this assumes that you started the database container and created the user as described in the previous post!)
Ok, now we are ready to read that document and create our vector embeddings. But how? In the previous post we manually created some excerpts, but now we want to read the whole document.
Enter Document Loaders! Take a look at that page, LangChain has hundreds of different document loaders that understand all kinds of documetn formats.
Let’s try the basic web loader, create and run this cell to install it:
Now create and run this cell to initialize the document loader:
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://www.gutenberg.org/cache/epub/2701/pg2701-images.html")
Now load the documents by running this cell:
docs = loader.load()
If you’d like, take a look at the result, by running this cell:
docs[0]
Well, that is just one big document, that is not so helpful, we want to split that document up into smaller chunks so we can create vectors for each smaller part. Let’s use a document splitter instead.
Install a splitter by running this cell:
%pip install -qU langchain-text-splitters
Note: Check out this page for more information about the available splitters. We are going to use the HTMLHeaderTextSplitter. Run this cell:
You’ll see a long list of Documents and if you look carefully, you can see that it has maintained the structure information.
Great! That’s a lot better.
Now, let’s suppose we wanted to constrain the size of the chunks. Some of those might be too big, we might want to split them even further. We can do that with a RecursiveCharacterTextSplitter.
Let’s say we wanted chunks no bigger than 500 characters, with an overlap of 30. Now this might not be a good idea, but just for the sake of the example, let’s do it by running this cell:
from langchain_community.vectorstores import oraclevs
from langchain_community.vectorstores.oraclevs import OracleVS
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain_core.documents import Document
from langchain_huggingface import HuggingFaceEmbeddings
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
vector_store = OracleVS.from_documents(
splits,
embedding_model,
client=connection,
table_name="moby_dick_500_30",
distance_strategy=DistanceStrategy.COSINE,
)
We are using the same model as we did in the previous post, but now we are passing in our splits that we just created – our 500 character long chunks of our larger chunks created from the HTML document respecting the document structure. And we called our vector store table moby_dick_500_30 to make it a little easier to remember what we put in there.
After that cell has finished (it might take a few minutes), you can take a look to see what is in the vector store by running this command in your terminal window:
docker exec -i db23ai sqlplus vector/vector@localhost:1521/FREEPDB1 <<EOF
select table_name from user_tables;
describe documents_cosine;
column id format a20;
column text format a30;
column metadata format a30;
column embedding format a30;
set linesize 150;
select * from moby_dick_500_30
fetch first 3 rows only;
EOF
You should get something similar to this:
Let’s try our searches again, run this cell:
query = 'Where is Rokovoko?'
print(vector_store.similarity_search(query, 1))
query2 = 'What does Ahab like to do after breakfast?'
print(vector_store.similarity_search(query2, 1))
You can change that 1 to a larger number now, since you have many more vectors, to see what you get!
Ok, now we have all the pieces we need and we are ready to implement the RAG!
The most basic way to implement RAG is to use a “retriever” – we can grab one from our vector store like this:
retriever = vector_store.as_retriever()
Try it out by asking a question:
docs = retriever.invoke("Where is Rokovoko?")
docs
You’ll get something like this:
Nearly there!
Now, we want to give the LLM a good prompt to tell it what to do, and include the retrieved documents. Let’s use a standard prompt for now:
You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
Question: (question goes here)
Context: (context goes here)
Answer:
Ok, now to put it all together. Now, in real life we’d probably want to use LangGraph at this point, and we’d want to think about including things like memory, ranking the results from the vector search, citations/references (“grounding” the answer), and streaming the output. But that’s all for another post! For now, let’s just do the most basic implementation:
AIMessage(content='Rokovoko is an island located far away to the West and South, as mentioned in relation to Queequeg, a native of the island. It is not found on any maps, suggesting it may be fictional.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 46, 'prompt_tokens': 402, 'total_tokens': 448, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_54eb4bd693', 'id': 'chatcmpl-BaW3g2omlCY0l6LwDkC9Ub8Ls3V88', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='run--86f14be2-9c8f-43c9-ae89-259db1c640bd-0', usage_metadata={'input_tokens': 402, 'output_tokens': 46, 'total_tokens': 448, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})
That’s a pretty good answer!
Well, there you go, we covered a lot of ground in this post, but that’s just a very basic RAG. Stay tuned to learn about implementing a more realistic RAG in the next post!
]]>https://redstack.dev/2025/05/23/basic-retrieval-augmented-generation-with-oracle-vector-store-in-langchain/feed/24082Getting started with Oracle Vector Store support in LangChain
https://redstack.dev/2025/05/16/getting-started-with-oracle-vector-store-support-in-langchain/
https://redstack.dev/2025/05/16/getting-started-with-oracle-vector-store-support-in-langchain/#commentsFri, 16 May 2025 22:00:53 +0000https://redstack.dev/?p=4041Continue reading →]]>In this post, I would like to show you the basics of how to use the Oracle Vector Store support in LangChain. I am using Visual Studio Code with the Python and Jupyter extensions from Microsoft installed. I will show more detailed usage in future posts!
Prefer to watch a video? Check it out here:
To get started, create a new project in Visual Studio code, and then create a new Jupyter Notebook using File > New File… then choose Jupyter Notebook as the type of file, and save your new file at getting_started.ipynb,
First, we need to set up the Python runtime environment. Click on the Select Kernel button (its on the top right). Select Python Environment then Create Python Environment. Select the option to create a Venv (Virtual Environment) and choose your Python interpreter. I recommend using at least Python 3.11. This will download all the necessary files and will take a minute or two.
In this example, we will use OpenAI for our chat model. You’ll need to get an API Key from OpenAI, which you can do by logging into https://platform.openai.com/settings/organization/api-keys and creating a key. Of course you could use a different model, including a self-hosted model so that you don’t have to send your data outside your organization. I’ll cover that in future posts, stay tuned!
In the first cell, check that the type is Python and enter this code:
%pip install -qU "langchain[openai]"
Press Shift+Enter or click on the Run icon to run this code block. This will also take a minute or so to install the LangChain library for OpenAI.
Now create a second cell and paste in this code:
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain.chat_models import init_chat_model
model = init_chat_model("gpt-4o-mini", model_provider="openai")
Run this block, and when it prompts you for your key, paste in the key, it will start with something like sk-proj and have a long string of mostly letters and numbers after that. This will save your key in the environment so that you don’t have to keep entering it each time.
Now, we are ready to talk to the LLM! Let’s try a simple prompt. Create a new cell and enter this code:
model.invoke("Hello, world!")
Run this cell and observe the output. It should look something like this:
Great, now we are ready to connect to a vector store. If you don’t already have one, start up an instance of Oracle Database 23ai in a container on your machine. Run this command in a terminal window (not the notebook)
This will start up an Oracle Database 23ai Free instance in a container. It will have a PDB called FREEPDB1 and the password for PDBADMIN (and SYS and SYSTEM) will be Welcome12345.
Now, run the following command to create an Oracle user with appropriate permissions to create a vector store:
docker exec -i db23ai sqlplus sys/Welcome12345@localhost:1521/FREEPDB1 as sysdba <<EOF
alter session set container=FREEPDB1;
create user vector identified by vector;
grant connect, resource, unlimited tablespace, create credential, create procedure, create any index to vector;
commit;
EOF
Let’s connect to the database! First we’ll isntall the oracledb library. Create a new cell and enter this code:
Now, import the things we will need by creating a new call with this code and running it:
from langchain_community.vectorstores import oraclevs
from langchain_community.vectorstores.oraclevs import OracleVS
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain_core.documents import Document
from langchain_huggingface import HuggingFaceEmbeddings
We are going to need some documents to load into the vector store, so let’s define some to use for an example. In real life, you’d probably want use your own non-public documents to load a vector store if you were building a chatbot or using retrieval augmented generation. Create and run a new call with this code:
documents_json_list = [
{
"id": "moby_dick_2701_P1",
"text": "Queequeg was a native of Rokovoko, an island far away to the West and South. It is not down in any map; true places never are.",
"link": "https://www.gutenberg.org/cache/epub/2701/pg2701-images.html#link2HCH0012",
},
{
"id": "moby_dick_2701_P2",
"text": "It was not a great while after the affair of the pipe, that one morning shortly after breakfast, Ahab, as was his wont, ascended the cabin-gangway to the deck. There most sea-captains usually walk at that hour, as country gentlemen, after the same meal, take a few turns in the garden.",
"link": "https://www.gutenberg.org/cache/epub/2701/pg2701-images.html#link2HCH0036",
},
{
"id": "moby_dick_2701_P3",
"text": "Now, from the South and West the Pequod was drawing nigh to Formosa and the Bashee Isles, between which lies one of the tropical outlets from the China waters into the Pacific. And so Starbuck found Ahab with a general chart of the oriental archipelagoes spread before him; and another separate one representing the long eastern coasts of the Japanese islands—Niphon, Matsmai, and Sikoke. ",
"link": "https://www.gutenberg.org/cache/epub/2701/pg2701-images.html#link2HCH0109",
},
]
Now, let’s load them into a LangChain documents list with some metadata. Create and run a cell with this code:
Let’s have a look in the database and see what was created. Run this code in your terminal:
docker exec -i db23ai sqlplus vector/vector@localhost:1521/FREEPDB1 <<EOF
select table_name from user_tables;
describe documents_cosine;
column id format a20;
column text format a30;
column metadata format a30;
column embedding format a30;
set linesize 150;
select * from documents_cosine;
EOF
You should see output similar to this:
SQL>
TABLE_NAME
--------------------------------------------------------------------------------
DOCUMENTS_COSINE
SQL> Name Null? Type
----------------------------------------- -------- ----------------------------
ID NOT NULL RAW(16)
TEXT CLOB
METADATA JSON
EMBEDDING VECTOR(768, FLOAT32)
SQL> SQL> SQL> SQL> SQL> SQL>
ID TEXT METADATA EMBEDDING
-------------------- ------------------------------ ------------------------------ ------------------------------
957B602A0B55C487 Now, from the South and West t {"id":"moby_dick_2701_P3","lin [9.29364376E-003,-5.70030287E-
he Pequod was drawing nigh to k":"https://www.gutenberg.org/ 002,-4.62282933E-002,-1.599499
Formosa and the Bash cache/epub/2701/pg27 58E-002,
A8A71597D56432FD Queequeg was a native of Rokov {"id":"moby_dick_2701_P1","lin [4.28722538E-002,-8.80071707E-
oko, an island far away to the k":"https://www.gutenberg.org/ 003,3.56001826E-003,6.765306E-
West and South. It cache/epub/2701/pg27 003,
E7675836CF07A695 It was not a great while after {"id":"moby_dick_2701_P2","lin [1.06763924E-002,3.91203648E-0
the affair of the pipe, that k":"https://www.gutenberg.org/ 04,-1.01576066E-002,-3.5316135
one morning shortly cache/epub/2701/pg27 7E-002,
Now, let’s do a vector similarity search. Create and run a cell with this code:
query = 'Where is Rokovoko?'
print(vector_store.similarity_search(query, 1))
query2 = 'What does Ahab like to do after breakfast?'
print(vector_store.similarity_search(query2, 1))
This will find the one (1) nearest match in each case. You should get an answer like this:
[Document(metadata={'id': 'moby_dick_2701_P1', 'link': 'https://www.gutenberg.org/cache/epub/2701/pg2701-images.html#link2HCH0012'}, page_content='Queequeg was a native of Rokovoko, an island far away to the West and South. It is not down in any map; true places never are.')]
[Document(metadata={'id': 'moby_dick_2701_P2', 'link': 'https://www.gutenberg.org/cache/epub/2701/pg2701-images.html#link2HCH0036'}, page_content='It was not a great while after the affair of the pipe, that one morning shortly after breakfast, Ahab, as was his wont, ascended the cabin-gangway to the deck. There most sea-captains usually walk at that hour, as country gentlemen, after the same meal, take a few turns in the garden.')]
Well, there you go, that’s the most basic example of creating a vector store, loading some documents into it and doing a simple similarity search. Stay tuned to learn about more advanced features!