<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jeferson Ferreira on Medium]]></title>
        <description><![CDATA[Stories by Jeferson Ferreira on Medium]]></description>
        <link>https://medium.com/@jefersonferr?source=rss-6752562df90b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_-h9WbYKgHOmKwbJ</url>
            <title>Stories by Jeferson Ferreira on Medium</title>
            <link>https://medium.com/@jefersonferr?source=rss-6752562df90b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:32:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jefersonferr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Three Security Layers Oracle AI Database 26ai Adds on Top of SQL Firewall]]></title>
            <link>https://medium.com/@jefersonferr/three-security-layers-oracle-ai-database-26ai-adds-on-top-of-sql-firewall-a134dd9250c3?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a134dd9250c3</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 19:41:28 GMT</pubDate>
            <atom:updated>2026-09-01T00:25:36.093Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical look at Deep Data Security, Data Redaction, and post-quantum TLS</p><p>The <a href="https://medium.com/@jefersonferr/oracle-sql-firewall-protecting-your-database-from-injection-in-5-minutes-984b84743815">SQL Firewall article</a> covered one layer of defense: guaranteeing that only approved SQL runs against the database. Three problems sit outside that guarantee. Approved SQL needs an identity behind it: a specific, verifiable person, rather than a shared database session that every end user borrows. Even with the right person identified and the right rows returned, some columns hold values that person has no business reading in full, and Firewall has no opinion about the contents of a result set. And algorithms that hold up against classical computers today can still leave traffic readable to a quantum computer twenty years from now.</p><p>Oracle AI Database 26ai addresses each of these with a distinct capability: Deep Data Security for identity-aware authorization, Data Redaction for value-level masking, and post-quantum cryptography for the wire and the disk. All three build on top of SQL Firewall, and each protects against a different failure.</p><h3>Moving authorization into the database with Deep Data Security</h3><p>A conventional application connects to Oracle through one privileged database account shared by every end user, and pushes authorization decisions into application code. A developer writes the filter that limits an employee to their own HR record, and it ships after review.</p><p>Agentic AI removes that predictability. When an agent builds SQL at runtime to answer a user’s question, there is no fixed query for anyone to review beforehand, and the agent still connects through the same privileged account the application always used. Oracle made this explicit in the announcement accompanying Deep Data Security’s general availability in 26ai: agents inherit the account’s full access, while leaving behind the discipline of a predefined query and the authorization logic that used to live in application code.</p><p>Deep Data Security (Deep Sec) moves that authorization into the database itself. It extends ideas Oracle DBAs already know from Virtual Private Database and Real Application Security, replacing PL/SQL-heavy policy functions with a declarative SQL object: the data grant.</p><p>A data grant is created with CREATE DATA GRANT. It reads close to a regular GRANT statement, except that it can restrict access down to individual columns, and the restriction is expressed as a WHERE predicate evaluated against the caller&#39;s identity at runtime rather than against a static role.</p><pre>CREATE OR REPLACE DATA GRANT hr.manager_direct_reports<br>    AS SELECT (ALL COLUMNS EXCEPT ssn), UPDATE (salary)<br>    ON hr.employees<br>    WHERE manager = ORA_END_USER_CONTEXT.username<br>    TO manager_role;</pre><p>This grant lets a manager see every column of their direct reports except SSN, and update only the salary column. If Marvin holds both manager_role and an equivalent grant for his own record, querying hr.employees returns his own row in full and his reports&#39; rows with SSN coming back as NULL instead of an error or a blank field. Deep Sec resolves multiple applicable roles with OR logic, so holding both roles only adds visibility, it never subtracts it.</p><p>The identity behind ORA_END_USER_CONTEXT.username doesn&#39;t come from a database login. It arrives as an OAuth2 token issued by an external identity provider, typically Microsoft Entra ID or OCI IAM, and gets propagated to the database on the connection through the JDBC, python-oracledb, or ODP.NET driver. Application roles from the identity provider map to Deep Sec data roles inside the database, so there is no need to provision every end user as a database account. python-oracledb 4.0 shipped a dedicated plugin for exactly this, letting a Python application attach an end-user security context to a pooled connection before running a query and clear it afterward.</p><p>Checking which data grants already exist on an object is a quick dictionary query:</p><pre>SELECT owner, object_owner, object_name, grant_name<br>FROM   dba_data_grants<br>WHERE  object_name = &#39;EMPLOYEES&#39;;</pre><p>The owner column identifies the schema that owns the data grant itself, while object_owner identifies the schema of the table or view being protected. The two aren&#39;t always the same schema, since one user&#39;s data grant can protect an object owned by someone else.</p><p>For an architecture where a single connection pool or an MCP server sits between an AI agent and the database, this changes where the authorization logic lives. It stops being a check every new endpoint has to reimplement, and becomes a property of the data itself, enforced the same way no matter what wrote the query.</p><h3>Data Redaction hides what Deep Sec already approved</h3><p>Deep Sec decides whether a row or column is visible at all. Data Redaction operates one layer further in: the row is visible, the column is visible, and the value still gets masked before it leaves the database. Take Patricia, an HR service desk agent whom Deep Sec authorizes to see every column of an employee record, SSN included. Data Redaction still returns her SSN with only the last few digits visible, because a separate redaction policy sits between her authorized access and the value Oracle actually returns.</p><p>Data Redaction is part of the Advanced Security option, which requires Enterprise Edition. Standard Edition rejects DBMS_REDACT.ADD_POLICY outright.</p><p>Data Redaction has existed since Oracle 12c and the core mechanism hasn’t changed: DBMS_REDACT.ADD_POLICY attaches a masking function to a column, and Oracle applies that function to the value at query time without touching the stored data.</p><pre>BEGIN<br>  DBMS_REDACT.ADD_POLICY(<br>    object_schema       =&gt; &#39;hr&#39;,<br>    object_name         =&gt; &#39;employees&#39;,<br>    column_name         =&gt; &#39;ssn&#39;,<br>    policy_name         =&gt; &#39;redact_ssn&#39;,<br>    function_type       =&gt; DBMS_REDACT.PARTIAL,<br>    function_parameters =&gt; &#39;VVVFVVFVVVV,VVV-VV-VVVV,*,1,5&#39;,<br>    expression          =&gt; &#39;1=1&#39;<br>  );<br>END;<br>/</pre><p>With the policy in place, Patricia queries the column exactly as before and gets a masked value back. The five leading digits come back as asterisks, and the last four stay readable so she can still confirm an identity over the phone. The hyphens survive because the F positions in the format string mark them as separators rather than data, which is why the masked value still looks like an SSN instead of a string of stars:</p><pre>SELECT ssn FROM hr.employees WHERE employee_id = 148;<br><br>SSN<br>-----------<br>***-**-6789</pre><p>The row on disk is untouched. A user holding EXEMPT REDACTION POLICY running the same query on the same row sees 123-45-6789, which is what makes this a display-time transformation rather than a second copy of the data.</p><p>Confirming which columns already carry a policy is just as direct:</p><pre>SELECT object_owner, object_name, column_name, function_type<br>FROM   redaction_columns<br>WHERE  object_name = &#39;EMPLOYEES&#39;;</pre><p>Pairing that with redaction_policies, which lists the policy name and its enabled state per object, is usually enough to answer &quot;is this column actually being masked right now&quot; without having to log in as a lower-privileged user to test it.</p><p>What 23ai and 26ai added is support in places the feature used to reject outright. Older releases raised ORA-28094 the moment a redacted column appeared inside a view, a GROUP BY, a DISTINCT, an ORDER BY, or a set operator, which forced developers to work around redaction instead of relying on it for anything beyond a flat SELECT. That restriction is gone: redacted columns now work inside views and inline views, and DISTINCT, GROUP BY, ORDER BY, and UNION all return correctly redacted results instead of erroring out. In practice, that means redaction can now sit underneath the reporting and analytics queries an agent tends to generate on its own, instead of breaking the moment someone adds a GROUP BY.</p><p>One caution carries over unchanged from earlier releases: Data Redaction targets read-mostly, call-center-style access. An application that writes back a value it just read as redacted will happily persist the masked characters over the real ones, so it still needs a genuine write path that never goes through the redacted view.</p><h3>Getting ahead of harvest-now-decrypt-later</h3><p>The first two layers assume an attacker already inside the query path. This one assumes an attacker who is just listening. Harvest now, decrypt later describes exactly that: record TLS traffic today, encrypted with algorithms like RSA or ECDHE that a sufficiently capable quantum computer could eventually break, and decrypt it once that computer exists. For data with a short shelf life this barely matters. For medical records, financial history, or anything with a multi-decade retention requirement, it means the theft already happened, even if nobody can read the file yet.</p><p>Take a health insurance claim stored under a multi-decade retention requirement. If that claim traveled over TLS protected only by ECDHE, and someone captured the traffic in 2026, a working quantum computer in 2035 would hand them a claim that’s still supposed to stay confidential for years afterward.</p><p>NIST closed the standards gap on August 13, 2024, finalizing three algorithms after an eight-year evaluation: ML-KEM (FIPS 203) for key exchange, ML-DSA (FIPS 204) for digital signatures, and SLH-DSA (FIPS 205) as a hash-based signature alternative resting on a more conservative security assumption than the lattice-based pair.</p><p>Oracle AI Database 26ai was among the first database platforms to ship quantum-safe TLS built on these standards. Two defaults changed with the release: TDE now uses AES-256 for both column and tablespace encryption, where 19c defaulted to AES-192 for columns and AES-128 for tablespaces, and TLS 1.3 gained support for ML-KEM key exchange alongside the existing ECDHE.</p><p>Oracle didn’t move straight to pure ML-KEM, and the reasoning is worth keeping in mind when configuring this. ECDHE carries decades of cryptanalysis and no known break. ML-KEM is sound by NIST’s own extensive review, but it is young by cryptographic standards and hasn’t had the same real-world exposure yet. Oracle’s hybrid mode runs both key exchanges in the same handshake and combines the two resulting keys into one session key, so the connection stays protected even if one of the two algorithms turns out to have a flaw nobody has found. Release 26.1 supports both hybrid and pure ML-KEM modes, selected through the TLS_KEY_EXCHANGE_GROUPS parameter in sqlnet.ora. Hybrid is already the default when the parameter is unset, so setting it explicitly is about pinning the behavior rather than enabling it.</p><p>Pinning it explicitly is a matter of sqlnet.ora:</p><pre>SSL_VERSION = TLSv1.3<br>TLS_KEY_EXCHANGE_GROUPS = hybrid,ml-kem,ec</pre><p>That covers the wire. The disk side of the same release change is easier to audit, because the algorithm in use is recorded in the data dictionary. V$TABLESPACE names the tablespaces, V$ENCRYPTED_TABLESPACES carries the algorithm, and TS# joins them:</p><pre>SELECT t.name AS tablespace_name,<br>       e.encryptionalg,<br>       e.status<br>FROM   v$tablespace t<br>JOIN   v$encrypted_tablespaces e ON t.ts# = e.ts#<br>ORDER  BY e.encryptionalg;<br><br>TABLESPACE_NAME   ENCRYPT  STATUS<br>----------------  -------  ----------<br>SALES_DATA        AES128   NORMAL<br>USERS             AES128   NORMAL<br>AUDIT_TS          AES256   NORMAL</pre><p>Only encrypted tablespaces appear here, so the inner join doubles as the filter. AES128 on the first two rows is the fingerprint of a database created under the old default rather than a deliberate choice anyone made, which is the common case in an estate that predates 26ai. STATUS reads NORMAL when nothing is in flight; during an online rekey it reports the conversion instead, so the same query serves to start the audit and to watch the migration finish.</p><p>Two things to know before running it. These are V$ views, so a developer who ran every earlier example in this article may still need SELECT granted on V_$ENCRYPTED_TABLESPACES. And in a CDB the result only reflects open containers, because the data comes from reading data file headers at open time. Run it in the root with PDBs closed and the list comes back short, which is the wrong kind of quiet answer for an audit.</p><p>TDE belongs to the same Advanced Security option. TLS itself carries no such restriction.</p><p>Anything still showing AES128 from a database created before the default changed can be moved forward without downtime:</p><pre>ALTER TABLESPACE users ENCRYPTION ONLINE USING &#39;AES256&#39; REKEY;</pre><p>The command works as written in ASM or wherever DB_CREATE_FILE_DEST is set. On plain filesystem storage it needs a FILE_NAME_CONVERT clause, because the conversion writes a converted copy of each data file to a new location before retiring the original, and the destination has to have room for a second copy of the tablespace. REKEY also assumes the tablespace is already encrypted, so the rows that came back from the previous query take REKEY and anything absent from that list takes ENCRYPT instead. If the conversion is interrupted, it resumes with ENCRYPTION ONLINE FINISH REKEY rather than starting over, which is what makes this survivable inside a real maintenance window.</p><p>None of this requires a quantum computer to exist yet to be worth doing. The traffic being harvested today is the traffic at risk, and the rekey work for a large tablespace is measured in hours or days once it starts, which is reason enough to check the algorithm column now rather than after a compliance deadline forces the question.</p><h3>What this doesn’t cover yet</h3><p>Put next to SQL Firewall, these three layers cover a wide surface: what SQL can run, who it runs as, what values come back, and how the wire traffic and the disk stay protected. One case this list doesn’t cover: authorization when an agent acts under its own service identity instead of impersonating an end user. That’s a different problem from the delegated-access case Deep Sec solves here, and it deserves its own article.</p><p>Adopting all three isn’t an all-at-once decision, and the order largely decides itself. Deep Sec goes first, because it is the only one of the three that changes how identity reaches the database: a token from the identity provider, a security context attached to the connection at the driver, application roles mapped to data roles. That path has to be right before a policy written on top of it means anything. Redaction follows without friction: it touches neither the schema nor the connection, so a column masked later behaves exactly as it would have if masked from the start. TLS and TDE sit outside that order entirely, since neither asks the application to notice anything changed. Both can start today, with the audit that costs a single query against v$encrypted_tablespaces.</p><h3>References</h3><ul><li><a href="https://medium.com/@jefersonferr/oracle-sql-firewall-protecting-your-database-from-injection-in-5-minutes-984b84743815">Oracle SQL Firewall: Protecting Your Database from Injection in 5 Minutes</a></li><li>Oracle: <a href="https://blogs.oracle.com/database/oracle-deep-data-security-is-now-available-in-oracle-ai-database-26ai">Oracle Deep Data Security Is Now Available in Oracle AI Database 26ai</a> (May 2026)</li><li>Oracle Documentation: <a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/ddscg/create-data-grants.html">Oracle Deep Data Security Guide — Create Data Grants</a></li><li>Sharad Chandran, Oracle Developers (Medium): <a href="https://medium.com/oracledevs/using-oracle-ai-database-deep-data-security-in-python-applications-bf84eb07f532">Using Oracle AI Database Deep Data Security in Python Applications</a> (May 2026)</li><li>ORACLE-BASE: <a href="https://oracle-base.com/articles/23/data-redaction-dbms_redact-enhancements-23">Data Redaction (DBMS_REDACT) Enhancements in Oracle Database 23ai/26ai</a></li><li>Oracle: <a href="https://blogs.oracle.com/database/oracle-ai-database-26ai-pqc">Securing Oracle AI Database 26ai for the Quantum Era</a></li><li>Oracle: <a href="https://blogs.oracle.com/database/hybrid-pqc">Both Is Better — Oracle AI Database 26ai Adds Hybrid-Mode Quantum-Resistant Support</a> (January 2026)</li><li>NIST: <a href="https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards">NIST Releases First 3 Finalized Post-Quantum Encryption Standards</a> (August 2024)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a134dd9250c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Your Schema AI-Ready with Oracle Database Annotations]]></title>
            <link>https://medium.com/@jefersonferr/making-your-schema-ai-ready-with-oracle-database-annotations-64a5c0449932?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/64a5c0449932</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[oracle-database]]></category>
            <category><![CDATA[select-ai]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 20:41:14 GMT</pubDate>
            <atom:updated>2026-07-06T20:41:14.805Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The real problem is not the absence of documentation. It is where that documentation lives. Comments about a schema usually live outside the database, scattered across wikis and Confluence pages, or simply in the memory of whoever built the tables years ago. When an AI agent or Select AI needs to generate SQL against a schema, it sees only table names and column names. Everything else is invisible. The result is SQL that runs without error and still answers the wrong question.</p><p>Annotations solve this by moving documentation inside the database itself: structured name-value pairs that any tool reading the data dictionary can query directly through SQL. Instead of a comment buried in a wiki page nobody opens before writing a query, the meaning of status = &#39;ERROR&#39; sits next to the column that defines it, and it never goes out of sync with the object it describes.</p><h3>Annotations vs. COMMENT</h3><p>COMMENT ON TABLE and COMMENT ON COLUMN store a single block of unstructured text per object. Annotations store multiple name-value pairs per object, and the meaning of each pair is defined by the application that uses it. A table can carry a description annotation, a displayannotation, and a domain-specific one such as allowed_values, all independent of each other. Both mechanisms can be used together on the same schema.</p><p>Annotations are not limited to tables and columns. Views, materialized views, indexes, and domains can carry them too, which matters for teams that expose reporting views to Select AI instead of the base tables directly.</p><p>Availability: annotations are a feature of Oracle Database 26ai, and this article assumes that version throughout.</p><p>A few constraints are worth knowing before writing the first annotation. An annotation name is mandatory, its value is optional, and there is no fixed list of names to choose from: display, description, and allowed_values are conventions the schema designer chooses, and the engine enforces none of them. Annotation values are stored as free text, up to 4000 characters each. If a name contains a space or matches a reserved word, it needs double quotes, the same rule that already applies to any other identifier in Oracle SQL.</p><h3>Adding Annotations in SQL</h3><p>Annotations can be declared together with a table:</p><pre>CREATE TABLE wf_process_instance (<br>    instance_id   NUMBER<br>        ANNOTATIONS (<br>            display      &#39;instance_id&#39;,<br>            description  &#39;Unique identifier for a BPMN process instance. Primary key.&#39;,<br>            ui_label     &#39;Instance ID&#39;<br>        ),<br>    process_name  VARCHAR2(200)<br>        ANNOTATIONS (<br>            display      &#39;process_name&#39;,<br>            description  &#39;Name of the BPMN process definition associated with this instance.&#39;,<br>            ui_label     &#39;Process Name&#39;<br>        ),<br>    status        VARCHAR2(50)<br>        ANNOTATIONS (<br>            display        &#39;status&#39;,<br>            description    &#39;Current execution status. Values: ACTIVE, PAUSED, COMPLETED, ERROR.&#39;,<br>            allowed_values &#39;ACTIVE,PAUSED,COMPLETED,ERROR&#39;<br>        )<br>)<br>ANNOTATIONS (<br>    display      &#39;workflow_instances&#39;,<br>    description  &#39;Process instances managed by the workflow engine.&#39;<br>);</pre><p>For existing tables, ALTER TABLE adds annotations without touching the data or requiring a rebuild:</p><p>sql</p><pre>ALTER TABLE wf_instance_variable ANNOTATIONS (<br>    ADD IF NOT EXISTS display      &#39;process_variables&#39;,<br>    ADD IF NOT EXISTS description  &#39;Runtime variables of a BPMN process instance. Key-value pairs resolved during activity execution.&#39;<br>);<br><br>ALTER TABLE wf_instance_variable MODIFY (<br>    variable_name ANNOTATIONS (<br>        ADD IF NOT EXISTS display     &#39;variable_name&#39;,<br>        ADD IF NOT EXISTS description &#39;Name of the process variable. Used as placeholder key in payloadTemplate expressions.&#39;<br>    ),<br>    variable_value ANNOTATIONS (<br>        ADD IF NOT EXISTS display     &#39;variable_value&#39;,<br>        ADD IF NOT EXISTS description &#39;Current value of the process variable at runtime.&#39;<br>    )<br>);</pre><p>ADD IF NOT EXISTSavoids an error when a migration script runs more than once, which matters for any team managing schema changes through Liquibase, Flyway, or a similar tool, since annotation changes should be versioned exactly like DDL. It is worth noting that IF NOT EXISTSonly prevents the error: if the annotation is already present, its value is left untouched. Correcting the wording of an existing annotation requires REPLACE.</p><p>Everything stored this way is queryable through the data dictionary:</p><pre>SELECT object_name, column_name,<br>       annotation_name, annotation_value<br>FROM   user_annotations_usage<br>WHERE  object_name IN (&#39;WF_PROCESS_INSTANCE&#39;, &#39;WF_INSTANCE_VARIABLE&#39;)<br>ORDER BY object_name, column_name, annotation_name;</pre><p>USER_ANNOTATIONS_USAGE lists every annotation applied to every object in the current schema, with one row per name-value pair. A second view, USER_ANNOTATIONS, lists the distinct annotation names in use without repeating them per object, which is useful for auditing naming consistency across a large schema. Both have ALL_ and DBA_ counterparts for cross-schema visibility.</p><h3>Annotations and Select AI</h3><p>This is where the investment pays off. Oracle’s own tutorial on this topic uses a deliberately obscure schema, with tables named E, T, R and columns named C1, C2, C3, to isolate the problem in the clearest possible way. That example works well for teaching the concept, but it does not reflect what most production schemas actually look like. Real schemas are rarely that bad, but they are rarely AI-ready either. A typical schema, from a system already in production, sits in that more common middle ground: the table and column names are reasonable for a developer reading the DDL, but they still carry no explicit information for a language model trying to translate a business question into SQL.</p><pre>SELECT AI SHOWSQL<br>  which payment process instances failed in the last 24 hours;</pre><p>Select AI has no way to know that status = &#39;ERROR&#39; represents a failure, or that process_name is the column that holds the name of the BPMN process. SHOWSQL is useful here precisely because it lets you inspect the generated statement before running it: the WHERE clause it produces may filter on the wrong column, or the query may execute successfully and still return zero rows, even though matching data exists. That last case is a false negative, and it is the most dangerous outcome, because nothing in the response tells you it is wrong.</p><p>With the column-level annotations shown above describing status (values: ACTIVE, PAUSED, COMPLETED, ERROR) and process_name (the BPMN process definition name):</p><pre>SELECT AI RUNSQL<br>  which payment process instances failed in the last 24 hours;</pre><p>The model now understands the domain and generates a correct predicate: status = &#39;ERROR&#39; combined with process_name LIKE &#39;%payment%&#39;, filtered by updated_at. Nothing about the physical schema changed. The only thing that changed is that the meaning of the columns is now stored somewhere the model, or any other tool connecting to the same database, can read it.</p><p>The same effect shows up on aggregation queries, where a wrong column choice is harder to notice because the query still returns a plausible-looking result. Asking, without annotations, for the count of instances grouped by outcome can silently group by the wrong column if the model cannot distinguish status from process_name or from a generic type column elsewhere in the schema. With allowed_values in place, the model has a closed list to match against and stops guessing which column represents an outcome.</p><h3>Two Paths to Add Annotations</h3><p>There are two practical ways to get annotations into a schema.</p><p>Manual SQL, through CREATE TABLE or ALTER TABLE as shown above, gives full control over wording and is trackable through a normal migration tool. This is the right approach for schemas under active version control, where every change already goes through a review process, and annotations are just one more column definition to review alongside the rest of the DDL.</p><p>AI Enrichment, available in SQL Developer for VS Code, offers a visual alternative built on top of the same annotation mechanism. It uses a language model to suggest display names and descriptions from the existing column names, sample data, and constraints, and it organizes tables into logical groups so an agent can navigate a large schema without scanning every object. This is the more practical route for legacy schemas with hundreds of tables, where writing ALTER TABLEby hand for every column is not a realistic amount of manual work, even if the resulting suggestions still need a human to review them before they are trusted.</p><h3>Annotations Beyond Select AI</h3><p>Annotations are not exclusive to Select AI. Any code generation tool, ORM, or modernization pipeline, including the kind built for large-scale legacy migrations, can read user_annotations_usage to generate UI labels, validation rules, and reference documentation automatically, without depending on configuration that lives outside the database and can silently drift out of sync with it.</p><h3>Conclusion</h3><p>The value of annotations comes from where the documentation lives: inside the database, next to the data, queryable by any tool that connects to it. Adding description, display, and allowed_values to the columns that actually need them is a small, incremental investment. It is also the minimum one required so that Select AI, autonomous agents, and code generation tools work with what the schema actually means, instead of guessing at it from names that were never meant to be self-explanatory.</p><h3>References</h3><ol><li>“Making Select AI Smarter with Database Annotations,” Oracle coretec blog, June 2026. <a href="https://blogs.oracle.com/coretec/making-select-ai-smarter-with-database-annotations">https://blogs.oracle.com/coretec/making-select-ai-smarter-with-database-annotations</a></li><li>Oracle Database SQL Language Reference, ALTER TABLE, annotations_clause. <a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/sqlrf/ALTER-TABLE.html">https://docs.oracle.com/en/database/oracle/oracle-database/26/sqlrf/ALTER-TABLE.html</a></li><li>Oracle AI Database, AI Enablement Guide 26ai, “What is AI Enrichment.” <a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/aienb/what-is-ai-enrichment.html">https://docs.oracle.com/en/database/oracle/oracle-database/26/aienb/what-is-ai-enrichment.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64a5c0449932" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observing and Exposing Event-Driven Microservices on OCI]]></title>
            <link>https://medium.com/@jefersonferr/observing-and-exposing-event-driven-microservices-on-oci-63c71a00dabb?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/63c71a00dabb</guid>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 18:38:40 GMT</pubDate>
            <atom:updated>2026-07-05T18:38:40.931Z</atom:updated>
            <content:encoded><![CDATA[<p><em>OpenTelemetry, SigNoz and APISIX with OBaaS</em></p><p>The Saga in the <a href="https://medium.com/@jefersonferr/choreographed-sagas-with-oracle-txeventq-cc86f9ddb4b1">previous article </a>runs correctly, but nothing about it is visible. When order-service, payment-service, and inventory-service cooperate across ORDER_EVENTS and PAYMENT_EVENTS, there is no single place to answer a simple question: where did this specific order spend its 200ms? OBaaS 2.1.0 provides OpenTelemetry auto-instrumentation and SigNoz as the trace and metrics backend out of the box. This article adds the wiring that TxEventQ, being JMS, requires beyond that platform default, plus an APISIX route that exposes the flow to external clients without losing the trace.</p><p>Anders Swanson at Oracle already covered a related but narrower problem: instrumenting a single Spring Boot service that produces and consumes its own TxEventQ point-to-point queue. The scope here is wider. The trace has to survive two asynchronous hops across three separate services, over pub/sub topics with durable subscriptions, instead of a single queue inside one app.</p><h3>Prerequisites</h3><ul><li>The three services from the previous article (order-service, payment-service, inventory-service), deployed and working</li><li>OBaaS <strong>2.1.0</strong>. OpenTelemetry Operator support for Java auto-instrumentation was added in this release. It is not present on 2.0.0. Confirm your platform version before following this article</li><li>micrometer-jakarta9 on the classpath of all three services (Spring Boot&#39;s dependency management resolves the version)</li></ul><h3>Section 1: What OBaaS 2.1.0 Adds</h3><p>Oracle describes OBaaS 2.1.0 as a platform modernization release covering several areas at once. Three changes matter for this article. First, Gateway API and Envoy Gateway became the default path for external access, and the NGINX Ingress Controller was deprecated: disabled by default, though still usable if explicitly enabled. Second, the OpenTelemetry Operator was added, providing Java auto-instrumentation as a platform capability instead of something each service configures for itself. Third, APISIX is unaffected by either change. Envoy Gateway handles cluster ingress and TLS termination, APISIX remains the API gateway layer with route-level plugins, and the two operate at different points in the request path.</p><p>The OBaaS team has documented the motivation for this observability shift directly. Before it, every new microservice meant hours of manual telemetry work: adding SDK dependencies, scattering metrics annotations through business logic, writing custom filters just to keep trace IDs in the logs. They call this the “Observability Tax.” The fix was standardizing on the OpenTelemetry Java Agent with SigNoz as the backend, currently at version 0.113.0.</p><h3>Section 2: Auto-Instrumentation via the OpenTelemetry Operator</h3><p>The mechanism is the standard Kubernetes OpenTelemetry Operator pattern: an Instrumentation custom resource named traces-instrumentation exists in the obaas namespace, and any pod annotated to reference it gets the Java agent injected during pod initialization, with no changes to the built JAR or Docker image.</p><pre># deployment for order-service, applied by oractl deploy<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: order-service<br>  namespace: application<br>spec:<br>  template:<br>    metadata:<br>      annotations:<br>        instrumentation.opentelemetry.io/inject-java: &quot;obaas/traces-instrumentation&quot;<br>    spec:<br>      containers:<br>        - name: order-service<br>          image: &lt;registry&gt;/order-service:latest<br>          env:<br>            - name: OTEL_SERVICE_NAME<br>              value: order-service</pre><p>OTEL_SERVICE_NAME is the one value worth setting explicitly per service: it is the name that shows up in SigNoz. Everything else, Collector endpoint and resource attributes included, is filled in by the platform’s standardized deployment templates once a service is identified as Spring Boot or Helidon. Apply the same annotation, with the corresponding service name, to payment-service and inventory-service.</p><p>With the agent attached, Spring MVC, JDBC, and outbound HTTP calls get instrumented automatically, with no code and no dependency to add. JMS is the exception. It needs one more step.</p><h3>Section 3: Making the Trace Survive the JMS Hop</h3><p>micrometer-jakarta9on the classpath is necessary but not sufficient. The Spring Framework instrumentation for jakarta.jms.Sessionproduces two observation types,jms.message.publishon the producer side and jms.message.process on the consumer side, and both require an explicit ObservationRegistryset on the component doing the work. Skip that step and the observation is a no-op: no span, no propagated traceparent.</p><p>For the producer side, order-service was relying on Spring Boot&#39;s autoconfigured JmsTemplate, which does not have an ObservationRegistry attached by default. It needs to be defined explicitly:</p><pre>@Configuration<br>public class JmsObservabilityConfig {<br>@Bean<br>    public JmsTemplate topicJmsTemplate(ConnectionFactory cf, ObservationRegistry registry) {<br>        JmsTemplate template = new JmsTemplate(cf);<br>        template.setPubSubDomain(true);           // ORDER_EVENTS / PAYMENT_EVENTS are Topics<br>        template.setObservationRegistry(registry); // required - classpath presence alone does nothing<br>        return template;<br>    }<br>}</pre><p>For the consumer side, the topicJmsFactory bean already defined in the previous article (Section 3, order-service) needs one added line:</p><pre>@Bean<br>public JmsListenerContainerFactory&lt;?&gt; topicJmsFactory(<br>        ConnectionFactory cf,<br>        DefaultJmsListenerContainerFactoryConfigurer configurer,<br>        ObservationRegistry registry) {<br>    var factory = new DefaultJmsListenerContainerFactory();<br>    configurer.configure(factory, cf);<br>    factory.setPubSubDomain(true);<br>    factory.setSubscriptionDurable(true);<br>    factory.setObservationRegistry(registry); // same requirement on the consumer side<br>    return factory;<br>}</pre><p>Apply the equivalent bean definitions in payment-service and inventory-service. ObservationRegistry itself does not need to be defined manually. Spring Boot’s Actuator autoconfiguration provides it as soon as micrometer-tracing-bridge-otel is on the classpath, which it is once the agent is attached, since the OpenTelemetry starter pulls it in transitively.</p><p>It’s roughly fifteen lines, written once per service, against telemetry code that used to be scattered across every business method. With it in place, a trace initiated at POST /orders crosses into payment-service when it dequeues ORDER_EVENTS, then into inventory-service when it dequeues PAYMENT_EVENTS. SigNoz shows the whole chain as a single trace:</p><pre>POST /orders (order-service)                                     ~200ms<br>  ├── INSERT orders (JDBC)<br>  ├── jms.message.publish → ORDER_EVENTS<br>  │<br>  └── jms.message.process ← ORDER_EVENTS (payment-service, subscription: payment-service-order-events)<br>        ├── UPDATE accounts (JDBC)<br>        ├── jms.message.publish → PAYMENT_EVENTS<br>        │<br>        └── jms.message.process ← PAYMENT_EVENTS (inventory-service, subscription: inventory-service-payment-events)<br>              └── UPDATE stock (JDBC)</pre><p>ORDER_EVENTSand PAYMENT_EVENTS are Topics rather than point-to-point Queues, so the jms.message.processspan is scoped to a durable subscription rather than to the queue itself. order-serviceand inventory-serviceboth consume PAYMENT_EVENTS, and in SigNoz they show up as two independent spans against two different subscription names, each with its own consumer lag and duration. A reader used to point-to-point JMS might expect a single shared span here; that’s not how it works with Topics.</p><h3>Section 4: A Business Metric — Compensation Rate</h3><p>The automatic spans answer “how long” and “where.” They do not answer “how often does this Saga compensate, and why.” That requires one manual observation, in the same listener already responsible for compensation in order-service:</p><pre>// PaymentEventListener — order-service<br>@JmsListener(destination = &quot;PAYMENT_EVENTS&quot;,<br>             containerFactory = &quot;topicJmsFactory&quot;,<br>             subscription = &quot;order-service-payment-events&quot;)<br>@Transactional<br>public void onPaymentEvent(PaymentResultEvent event) {<br>    if (PaymentStatus.FAILED == event.status()) {<br>        orderRepository.updateStatus(event.orderId(), OrderStatus.CANCELLED);<br><br>Observation.createNotStarted(&quot;saga.compensation&quot;, observationRegistry)<br>            .lowCardinalityKeyValue(&quot;reason&quot;, event.reason())      // e.g. INSUFFICIENT_FUNDS<br>            .lowCardinalityKeyValue(&quot;saga.type&quot;, &quot;order-payment&quot;)<br>            .observe(() -&gt; log.warn(&quot;Saga compensated for order {}&quot;, event.orderId()));<br>    }<br>}</pre><p>lowCardinalityKeyValuebecomes a metric tag, filterable in SigNoz. highCardinalityKeyValue the specific orderIdin this case, is attached to the trace only, which avoids a metric cardinality explosion. A single Observation call produces a timer, a counter, and a trace span from the same block of code, so there’s no separate metrics API to learn on top of the tracing one.</p><h3>Section 5: Exposing the Flow Through APISIX</h3><p>APISIX routes to order-servicethrough Eureka discovery, so there are no hardcoded pod IPs and no manual upstream updates when a pod restarts. This article adds JWT authentication, a per-consumer rate limit, and trace propagation on top of that route.</p><p><strong>Exposing the JWT signing endpoint.</strong> As of the current jwt-auth plugin, /apisix/plugin/jwt/sign is not exposed by default; it has to be published explicitly through the public-api plugin:</p><pre>curl &quot;http://localhost:9180/apisix/admin/routes/jwt-sign&quot; \<br>     -H &quot;X-API-KEY: ${APISIX_ADMIN_KEY}&quot; -X PUT -d &#39;{<br>  &quot;uri&quot;: &quot;/apisix/plugin/jwt/sign&quot;,<br>  &quot;plugins&quot;: { &quot;public-api&quot;: {} }<br>}&#39;</pre><p><strong>Enabling the </strong><strong>opentelemetry plugin globally</strong> and pointing it at the same Collector the services already export to:</p><pre>curl &quot;http://localhost:9180/apisix/admin/plugin_metadata/opentelemetry&quot; \<br>     -H &quot;X-API-KEY: ${APISIX_ADMIN_KEY}&quot; -X PUT -d &#39;{<br>  &quot;trace_id_source&quot;: &quot;x-request-id&quot;,<br>  &quot;resource&quot;: { &quot;service.name&quot;: &quot;apisix-gateway&quot; },<br>  &quot;collector&quot;: { &quot;address&quot;: &quot;otel-collector.obaas:4318&quot; }<br>}&#39;</pre><p><strong>Creating a consumer and a JWT credential.</strong> Consumers carry credentials as a sub-resource, keyed independently of the consumer itself:</p><pre>curl &quot;http://localhost:9180/apisix/admin/consumers&quot; \<br>     -H &quot;X-API-KEY: ${APISIX_ADMIN_KEY}&quot; -X PUT -d &#39;{<br>  &quot;username&quot;: &quot;saga-demo-client&quot;<br>}&#39;<br><br>curl &quot;http://localhost:9180/apisix/admin/consumers/saga-demo-client/credentials&quot; \<br>     -H &quot;X-API-KEY: ${APISIX_ADMIN_KEY}&quot; -X PUT -d &#39;{<br>  &quot;id&quot;: &quot;cred-saga-demo-jwt&quot;,<br>  &quot;plugins&quot;: {<br>    &quot;jwt-auth&quot;: {<br>      &quot;key&quot;: &quot;saga-demo-key&quot;,<br>      &quot;secret&quot;: &quot;${JWT_SECRET}&quot;,<br>      &quot;algorithm&quot;: &quot;HS256&quot;<br>    }<br>  }<br>}&#39;</pre><p><strong>Creating the route. </strong>The limit-reqschema takes key_typeas either varor var_combination. The value being rate-limited by, consumer_name in this case, goes in the key field, separate from key_type. The plugin’s default rejected_codeis 503; set it explicitly to get 429 instead:</p><pre>curl &quot;http://localhost:9180/apisix/admin/routes/orders-route&quot; \<br>     -H &quot;X-API-KEY: ${APISIX_ADMIN_KEY}&quot; -X PUT -d &#39;{<br>  &quot;uri&quot;: &quot;/api/orders*&quot;,<br>  &quot;methods&quot;: [&quot;GET&quot;, &quot;POST&quot;],<br>  &quot;upstream&quot;: {<br>    &quot;type&quot;: &quot;roundrobin&quot;,<br>    &quot;discovery_type&quot;: &quot;eureka&quot;,<br>    &quot;service_name&quot;: &quot;ORDER-SERVICE&quot;<br>  },<br>  &quot;plugins&quot;: {<br>    &quot;jwt-auth&quot;: {},<br>    &quot;limit-req&quot;: {<br>      &quot;rate&quot;: 100,<br>      &quot;burst&quot;: 20,<br>      &quot;key_type&quot;: &quot;var&quot;,<br>      &quot;key&quot;: &quot;consumer_name&quot;,<br>      &quot;rejected_code&quot;: 429<br>    },<br>    &quot;opentelemetry&quot;: {<br>      &quot;sampler&quot;: { &quot;name&quot;: &quot;always_on&quot; }<br>    }<br>  }<br>}&#39;</pre><p>Each plugin has a separate job here.jwt-authvalidates the token before the request reaches order-service, so the service itself carries no authentication logic. limit-req caps each consumer at 100 requests per second with a burst of 20, returning 429 once that’s exceeded. opentelemetryinjects traceparentinto the outbound request, which makes the gateway span the parent of the order-service HTTP span instead of letting the trace start inside the service.</p><h3>Section 6: Validating End to End</h3><pre># Sign a token for the consumer created above<br>export TOKEN=$(curl -s &quot;http://&lt;apisix-external-ip&gt;/apisix/plugin/jwt/sign?key=saga-demo-key&quot;)<br><br># Happy path<br>curl -s -X POST http://&lt;apisix-external-ip&gt;/api/orders \<br>     -H &quot;Authorization: Bearer $TOKEN&quot; \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;customerId&quot;: &quot;C001&quot;, &quot;items&quot;: [{&quot;productId&quot;:&quot;P001&quot;,&quot;qty&quot;:2}], &quot;total&quot;: 150.00}&#39;<br># No token - should return 401<br>curl -s http://&lt;apisix-external-ip&gt;/api/orders<br># {&quot;message&quot;:&quot;Missing JWT token in request&quot;}</pre><p>In SigNoz, the Traces tab for order-service should show a root span from apisix-gateway, parenting the POST /orders span, followed by the cross-service chain from Section 3. The Metrics tab exposes http.server.request.duration at the usual percentiles for order-service, and the custom saga.compensation counter, filterable by reason. Sending more than 100 requests per second from the same consumer should produce visible 429 responses at the gateway, distinguishable in the same trace view from failures originating inside the services.</p><h3>What This Covers and What It Does Not</h3><p>The Saga from the previous article is now traceable across all three services and carries one business metric beyond the automatic ones. It also sits behind a gateway that authenticates requests, enforces the rate limit, and keeps the trace intact. The idempotency gap noted in the previous article is still there: payment-servicecan still double-debit on message redelivery. This work makes that failure mode visible faster. Fixing it remains a separate problem.</p><h3>References</h3><ul><li>Choreographed Sagas with Oracle TxEventQ — <a href="https://medium.com/@jefersonferr/choreographed-sagas-with-oracle-txeventq-cc86f9ddb4b1">https://medium.com/@jefersonferr/choreographed-sagas-with-oracle-txeventq-cc86f9ddb4b1</a></li><li>Medium (OBaaS Team), Observability the Smart Way: Automating Metrics in Java Microservices — <a href="https://medium.com/@DatabaseDoug/observability-the-smart-way-automating-metrics-in-java-microservices-2f82340114cb">https://medium.com/@DatabaseDoug/observability-the-smart-way-automating-metrics-in-java-microservices-2f82340114cb</a></li><li>Oracle Developers Blog, What’s New in Oracle Backend for Microservices and AI 2.1.0 — <a href="https://blogs.oracle.com/developers/whats-new-in-oracle-backend-for-microservices-and-ai-2-1-0">https://blogs.oracle.com/developers/whats-new-in-oracle-backend-for-microservices-and-ai-2-1-0</a></li><li>Oracle Backend for Microservices and AI, Release Notes — <a href="https://oracle.github.io/microservices-datadriven/spring/release-notes/">https://oracle.github.io/microservices-datadriven/spring/release-notes/</a></li><li>Spring Framework Docs, Observability Support — <a href="https://docs.spring.io/spring-framework/reference/integration/observability.html">https://docs.spring.io/spring-framework/reference/integration/observability.html</a></li><li>Spring Boot Docs, Observability — <a href="https://docs.spring.io/spring-boot/reference/actuator/observability.html">https://docs.spring.io/spring-boot/reference/actuator/observability.html</a></li><li>Apache APISIX Docs, opentelemetry Plugin — <a href="https://apisix.apache.org/docs/apisix/plugins/opentelemetry/">https://apisix.apache.org/docs/apisix/plugins/opentelemetry/</a></li><li>Apache APISIX Docs, jwt-auth Plugin — <a href="https://apisix.apache.org/docs/apisix/plugins/jwt-auth/">https://apisix.apache.org/docs/apisix/plugins/jwt-auth/</a></li><li>Apache APISIX Docs, limit-req Plugin — <a href="https://apisix.apache.org/docs/apisix/plugins/limit-req/">https://apisix.apache.org/docs/apisix/plugins/limit-req/</a></li><li>Apache APISIX Docs, public-api Plugin — <a href="https://apisix.apache.org/docs/apisix/plugins/public-api/">https://apisix.apache.org/docs/apisix/plugins/public-api/</a></li><li>CloudBank AI, Explore APISIX API Gateway — <a href="https://oracle.github.io/microservices-datadriven/cloudbank/backend/apisix/index.html">https://oracle.github.io/microservices-datadriven/cloudbank/backend/apisix/index.html</a></li><li>Anders Swanson, Tracing a Spring Boot JMS app with Oracle Database Free — <a href="https://andersswanson.dev/2025/10/07/tracing-a-spring-boot-jms-app-with-oracle-database-free/">https://andersswanson.dev/2025/10/07/tracing-a-spring-boot-jms-app-with-oracle-database-free/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63c71a00dabb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choreographed Sagas with Oracle TxEventQ]]></title>
            <link>https://medium.com/@jefersonferr/choreographed-sagas-with-oracle-txeventq-cc86f9ddb4b1?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc86f9ddb4b1</guid>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[autonomous-database]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 00:24:33 GMT</pubDate>
            <atom:updated>2026-07-03T00:24:33.862Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Spring Boot microservices on ADB 26ai</em></p><p>Synchronous REST between microservices creates temporal coupling. When a downstream service is unavailable, the entire transaction fails. The common workaround is to update the database and then publish an event to an external broker like Kafka or RabbitMQ, but that introduces the dual-write problem: two independent operations where any failure between them leaves state and messaging out of sync. The Transactional Outbox pattern addresses this, but it requires a relay component (Debezium or a polling job) that adds operational overhead.</p><p>Oracle Transactional Event Queues (TxEventQ) solves the problem at the root. Enqueue and DML participate in the same local Oracle transaction. There are not two operations. There is one.</p><p>This article walks through a working implementation of a choreographed Saga using three Spring Boot microservices connected to Oracle ADB 26ai via oracle-spring-boot-starter-aqjms. By the end, you will have a complete flow: order creation, payment debit, inventory reservation, and compensation on payment failure. None of it needs an external broker, an Outbox relay, or distributed locks.</p><h3>Prerequisites</h3><ul><li>ADB 26ai instance available on OCI with the wallet downloaded, or OBaaS provisioned</li><li>Java 21, Maven 3.9+</li><li>oractl CLI for OBaaS deployment, or direct JDBC access to ADB</li></ul><p><strong>A note on naming:</strong> In October 2025 at Oracle AI World, Oracle Database 23ai was renamed Oracle AI Database 26ai. Internally this is a Release Update (version 23.26.0), not a major upgrade. Existing ADB 23ai instances on OCI were converted automatically. All Spring Boot code and TxEventQ configuration that worked on 23ai runs on 26ai without any changes.</p><h3>Section 1: Oracle TxEventQ on ADB 26ai</h3><h3>Background and positioning</h3><p>Advanced Queuing has been part of Oracle since version 8.0. In 12.2, sharded queues were introduced. In 21c the engine was renamed TxEventQ, gaining an in-memory, partitioned architecture with substantially higher throughput. On 23ai and 26ai, TxEventQ added a Kafka Java client (okafka), ORDS REST APIs, and sessionless transaction support.</p><p>Two properties matter most for this article.</p><p><strong>Native transactionality.</strong> Enqueue and dequeue are part of the same local Oracle transaction. If an INSERT into the orders table rolls back, the event enqueue rolls back with it. There is no secondary system to synchronize.</p><p><strong>Outbox without Outbox.</strong> The Transactional Outbox pattern solves the dual-write problem by making the event a row in a database table and using a relay process to forward it to the broker. TxEventQ delivers the same guarantee, consistency between persistent state and message, but the queue itself is the transactional mechanism. There’s no intermediate table and no relay job like Debezium to keep running.</p><p><strong>Why this works without XA.</strong> A reader coming from JEE or general JMS + JDBC experience will reasonably ask: how can a JDBC INSERT and a JMS send share a transaction without a distributed transaction coordinator? The answer is specific to Oracle AQ/JMS: oracle-spring-boot-starter-aqjms builds its ConnectionFactory on top of the same UCP-managed JDBC connection used by the DataSource. Enqueue and DML run on the same Oracle session, so a single local @Transactional covers both. No JtaTransactionManager, no two-phase commit needed. This is a property of the AQ/JMS driver, not a general guarantee of Spring JMS; swapping in a different JMS provider (ActiveMQ, a standalone broker) would reintroduce the dual-write problem this article opened with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LwVMun5bmFjX-bWP_Zmrvg.png" /><figcaption>Figure 01 — TxEventQ vs. AQ Classic vs. Kafka: a decision table</figcaption></figure><p>If the system of record is ADB 26ai, TxEventQ is the natural choice. It eliminates an entire infrastructure component and inherits the database’s HA, backup, and security posture automatically.</p><h3>Spring Boot integration options</h3><p>Three integration paths are available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJNN1nMsEfxLxXAb_hYcvg.png" /><figcaption>Figure 02 — Spring Boot integration options (Starter/API/Best for)</figcaption></figure><p>This article uses Spring JMS with oracle-spring-boot-starter-aqjms. The code is direct, the connection between the database transaction and the message is explicit, and it is the same starter used in the CloudBank reference implementation for check processing.</p><h3>Maven dependencies</h3><p>The current version on Maven Central as of June 2026:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.oracle.database.spring&lt;/groupId&gt;<br>    &lt;artifactId&gt;oracle-spring-boot-starter-aqjms&lt;/artifactId&gt;<br>    &lt;version&gt;26.2.1&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;!-- UCP is a transitive dependency of aqjms, but declaring it explicitly<br>     allows pool configuration in application.yaml --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.oracle.database.spring&lt;/groupId&gt;<br>    &lt;artifactId&gt;oracle-spring-boot-starter-ucp&lt;/artifactId&gt;<br>    &lt;version&gt;26.2.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>Connecting to ADB 26ai via Wallet</h3><p>application.yaml:</p><pre>spring:<br>  datasource:<br>    url: jdbc:oracle:thin:@${TNS_NAME}?TNS_ADMIN=${WALLET_DIR}<br>    username: ${DB_USER}<br>    password: ${DB_PASSWORD}<br>    driver-class-name: oracle.jdbc.OracleDriver<br>    type: oracle.ucp.jdbc.PoolDataSourceImpl<br>    oracleucp:<br>      connection-factory-class-name: oracle.jdbc.pool.OracleDataSource<br>      connection-pool-name: saga-demo-pool<br>      initial-pool-size: 5<br>      min-pool-size: 5<br>      max-pool-size: 20</pre><p>On OBaaS, TNS_NAME, WALLET_DIR, DB_USER, and DB_PASSWORD are injected via Kubernetes Secret by oractl. The developer does not handle the wallet directly.</p><h3>Topic provisioning</h3><p>Topics must be created before the first deploy. OBaaS does not create queues automatically. This DDL is run once by the schema owner:</p><pre>-- Minimum grants for the application schema<br>GRANT aq_user_role          TO saga_demo;<br>GRANT EXECUTE ON dbms_aq    TO saga_demo;<br>GRANT EXECUTE ON dbms_aqadm TO saga_demo;<br>GRANT EXECUTE ON dbms_aqin  TO saga_demo;<br>GRANT EXECUTE ON dbms_aqjms TO saga_demo;<br>GRANT EXECUTE ON dbms_teqk  TO saga_demo;<br><br>-- Order topic (pub/sub: multiple_consumers =&gt; TRUE)<br>-- max_retries controls how many failed dequeue attempts a message tolerates<br>-- before it is moved to the queue&#39;s exception queue (see Section 4).<br>BEGIN<br>  DBMS_AQADM.CREATE_TRANSACTIONAL_EVENT_QUEUE(<br>    queue_name         =&gt; &#39;SAGA_DEMO.ORDER_EVENTS&#39;,<br>    multiple_consumers =&gt; TRUE,<br>    max_retries        =&gt; 5<br>  );<br>  DBMS_AQADM.START_QUEUE(queue_name =&gt; &#39;SAGA_DEMO.ORDER_EVENTS&#39;);<br>  DBMS_AQADM.CREATE_TRANSACTIONAL_EVENT_QUEUE(<br>    queue_name         =&gt; &#39;SAGA_DEMO.PAYMENT_EVENTS&#39;,<br>    multiple_consumers =&gt; TRUE,<br>    max_retries        =&gt; 5<br>  );<br>  DBMS_AQADM.START_QUEUE(queue_name =&gt; &#39;SAGA_DEMO.PAYMENT_EVENTS&#39;);<br>END;<br>/</pre><p>multiple_consumers =&gt; TRUE is required for pub/sub semantics: one producer, multiple consumers. With FALSE (the default), the queue is point-to-point: the first consumer to dequeue a message removes it. For a Saga where more than one service may need to react to the same event, TRUE is mandatory.</p><p><strong>A detail that trips people up:</strong> CREATE_TRANSACTIONAL_EVENT_QUEUE has no queue_table parameter. Unlike classic AQ, where you call CREATE_QUEUE_TABLE and CREATE_QUEUE separately and choose the table name yourself, TxEventQ generates the underlying queue table automatically. The SQL examples later in this article (Sections 4 and 5) query that table directly, so you need to look up its actual name rather than guessing it from the queue name:</p><pre>SELECT name, queue_table, queue_type<br>FROM   user_queues<br>WHERE  name IN (&#39;ORDER_EVENTS&#39;, &#39;PAYMENT_EVENTS&#39;);</pre><p>Run this once after provisioning and keep the queue_table values handy. They are what the monitoring queries in Sections 4 and 5 actually need.</p><h3>Section 2: The Choreographed Saga</h3><h3>When to use Saga and when not to</h3><p>Saga is for long-running transactions that span multiple services with independent persistent state. For local operations, Spring’s @Transactional is sufficient. For cross-service queries, synchronous REST works. Saga applies when a command changes state in two or more services and a failure in any step requires rollback of the preceding steps.</p><p>Two variants exist:</p><p><strong>Choreographed</strong> (this article): each service reacts to events and publishes the next one. No central coordinator. Straightforward for linear flows. Compensation is distributed: each service is responsible for undoing its own state.</p><p><strong>Orchestrated with MicroTx/LRA</strong> (referenced, not implemented here): a central coordinator (Oracle MicroTx Free, included with OBaaS) implements the Eclipse MicroProfile LRA spec. Annotations @LRA, @Complete, @Compensate. Appropriate when the flow has many participants or complex branching conditions. CloudBank Module 5 demonstrates this approach for account transfers.</p><h3>The system being built</h3><p>Three Spring Boot services over a shared ADB 26ai instance:</p><h3>Sequence: happy path</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehKAmICbUVVMNteNRF74qQ.png" /><figcaption>Figure 03 — Sequence: happy path</figcaption></figure><h3>Sequence: failure path (insufficient balance)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ5As1SinJUkpQDk3ifQLw.png" /><figcaption>Figure 04 — Sequence: failure path (insufficient balance)</figcaption></figure><p>The core point in both diagrams: at no step does an operation occur outside a local transaction. The entire flow runs with Spring’s @Transactional, the same mechanism used for ordinary database operations.</p><h3>Section 3: Service Implementations</h3><h3>order-service: producer and compensation consumer</h3><p><strong>JMS bean configuration.</strong> These beans are required. The ConnectionFactory and the DataSource share the same underlying UCP connection so that enqueue and DML participate in the same transaction (see the &quot;Why this works without XA&quot; note in Section 1).</p><p>There is a second requirement that is easy to miss: both ORDER_EVENTS and PAYMENT_EVENTS were created with multiple_consumers =&gt; TRUE, which makes them behave as JMS Topics, not Queues. Spring&#39;s DefaultJmsListenerContainerFactory assumes Queue (point-to-point) semantics unless told otherwise. Without setPubSubDomain(true) and a durable subscription name per consumer, two services listening on the same destination (order-service and inventory-service both consume PAYMENT_EVENTS) would compete for the same messages instead of each receiving its own copy.</p><pre>@SpringBootApplication<br>@EnableJms<br>public class OrderServiceApplication {<br>@Bean<br>    public JmsListenerContainerFactory&lt;?&gt; topicJmsFactory(<br>            ConnectionFactory cf,<br>            DefaultJmsListenerContainerFactoryConfigurer configurer) {<br>        var factory = new DefaultJmsListenerContainerFactory();<br>        configurer.configure(factory, cf);<br>        factory.setPubSubDomain(true);        // multiple_consumers =&gt; TRUE requires Topic semantics<br>        factory.setSubscriptionDurable(true);  // survives listener restarts without losing messages<br>        return factory;<br>    }<br>    @Bean<br>    public MessageConverter messageConverter() {<br>        var converter = new MappingJackson2MessageConverter();<br>        converter.setTargetType(MessageType.TEXT);<br>        converter.setTypeIdPropertyName(&quot;_type&quot;);<br>        return converter;<br>    }<br>}</pre><p><strong>Placing an order: INSERT and ENQUEUE in the same </strong><strong>@Transactional:</strong></p><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {<br><br>private final OrderRepository orderRepository;<br>    private final JmsTemplate jmsTemplate;<br>    @Transactional          // one transaction: database + queue<br>    public Order placeOrder(OrderRequest req) {<br>        Order order = orderRepository.save(<br>            Order.of(req, OrderStatus.PENDING)<br>        );<br>        jmsTemplate.convertAndSend(<br>            &quot;ORDER_EVENTS&quot;,<br>            new OrderPlacedEvent(order.getId(), req.getItems(), req.getTotal())<br>        );<br>        return order;       // if any line fails: full rollback<br>    }<br>}</pre><p>If orderRepository.save succeeds but convertAndSend throws, the transaction rolls back: the row is not persisted and the event is not enqueued. If the reverse happens (enqueue succeeds but the save fails), the same rollback applies. The two operations are atomically bound.</p><p><strong>Compensation: consuming the payment failure event:</strong></p><pre>@Component<br>@RequiredArgsConstructor<br>public class PaymentEventListener {<br>private final OrderRepository orderRepository;<br>    @JmsListener(<br>        destination = &quot;PAYMENT_EVENTS&quot;,<br>        containerFactory = &quot;topicJmsFactory&quot;,<br>        subscription = &quot;order-service-payment-events&quot;)<br>    @Transactional<br>    public void onPaymentEvent(PaymentResultEvent event) {<br>        if (PaymentStatus.FAILED == event.status()) {<br>            orderRepository.updateStatus(event.orderId(), OrderStatus.CANCELLED);<br>        }<br>        // CONFIRMED: order-service takes no action;<br>        // inventory-service handles that step instead<br>    }<br>}</pre><h3>payment-service: consumer and producer</h3><p>The critical moment: account debit and result publication in the same transaction. If the debit fails (for example, an OptimisticLockException on the account row), the result message is not sent and the input message from ORDER_EVENTS is not dequeued; it will be redelivered.</p><pre>@JmsListener(<br>    destination = &quot;ORDER_EVENTS&quot;,<br>    containerFactory = &quot;topicJmsFactory&quot;,<br>    subscription = &quot;payment-service-order-events&quot;)<br>@Transactional<br>public void onOrderPlaced(OrderPlacedEvent event) {<br>    boolean debited = accountService.tryDebit(event.orderId(), event.total());<br>PaymentResultEvent result = debited<br>        ? PaymentResultEvent.confirmed(event.orderId())<br>        : PaymentResultEvent.failed(event.orderId(), &quot;INSUFFICIENT_FUNDS&quot;);<br>    jmsTemplate.convertAndSend(&quot;PAYMENT_EVENTS&quot;, result);<br>    // debit + enqueue: one transaction.<br>    // Failure in either → rollback of both.<br>}</pre><p>This is where TxEventQ earns its keep. In a Kafka-based implementation, the debit would commit to the database and then the result would be sent to the broker as a separate operation. A crash between the two leaves an order permanently in PENDING state with money already debited. Here, the debit and the message are one atomic unit.</p><p><strong>One gap this code leaves open:</strong> the transactional guarantee covers atomicity between debit and enqueue, not idempotency of tryDebit itself. If payment-service crashes after committing but before the container acknowledges the original ORDER_EVENTS message, TxEventQ redelivers it, which is normal at-least-once messaging behavior, not a defect. tryDebit as shown would apply the debit twice on redelivery. A production version needs a dedup check keyed on orderId (a unique constraint on a processed-events table, or a status check before debiting) before this code is safe to run unattended.</p><h3>inventory-service: final consumer</h3><p>The simplest of the three. It only reserves stock on the happy path. In the failure path, inventory was never touched, so there is nothing to compensate.</p><pre>@JmsListener(<br>    destination = &quot;PAYMENT_EVENTS&quot;,<br>    containerFactory = &quot;topicJmsFactory&quot;,<br>    subscription = &quot;inventory-service-payment-events&quot;)<br>@Transactional<br>public void onPaymentResult(PaymentResultEvent event) {<br>    if (PaymentStatus.CONFIRMED == event.status()) {<br>        inventoryService.reserve(event.orderId());<br>    }<br>    // FAILED: inventory unchanged, no compensation needed<br>}</pre><h3>Section 4: Exception Queues</h3><p>Every AQ and TxEventQ queue table tracks a RETRY_COUNT per message and compares it against the max_retries value set on CREATE_TRANSACTIONAL_EVENT_QUEUE back in Section 2.4. Once RETRY_COUNT exceeds MAX_RETRIES, Oracle moves the message out of the normal queue and into that queue table&#39;s exception queue automatically. This is documented AQ behavior, not something specific to TxEventQ.</p><p>This matters for the Saga: if payment-service is down for a sustained period, or if onOrderPlaced keeps throwing (a bug, not just a transient failure), messages in ORDER_EVENTS accumulate retries and eventually land in the exception queue. The corresponding order stays in PENDING, neither confirmed nor cancelled. Monitoring RETRY_COUNT is part of operating the Saga correctly, not an optional extra.</p><pre>-- List every queue in the schema, including the default exception queue<br>-- for each queue table. QUEUE_TYPE distinguishes NORMAL_QUEUE from EXCEPTION_QUEUE.<br>SELECT name, queue_table, queue_type<br>FROM   user_queues<br>ORDER  BY queue_table, queue_type;</pre><p>Once you have the queue_table value for ORDER_EVENTS, that same automatically generated view exposes every message with its retry count:</p><pre>-- Replace &lt;queue_table&gt; with the value returned above for ORDER_EVENTS<br>SELECT msg_id, enq_time, msg_state, retry_count, user_data<br>FROM   AQ$&lt;queue_table&gt;<br>ORDER  BY enq_time DESC;</pre><p>MSG_ID, MSG_STATE, USER_DATA, and RETRY_COUNT are documented columns of the AQ$&lt;queue_table&gt; view. RETRY_COUNT climbing toward the max_retries value configured in Section 2.4 is the signal that a message is close to, or already past, being moved to the exception queue.</p><p>The ability to inspect queue content with standard SQL is a practical advantage over Kafka. No separate console, no additional tooling: the same SQL client used for application data works here.</p><h3>Section 5: Testing the Flow</h3><h3>Happy path</h3><pre># Place an order (account has sufficient balance)<br>curl -s -X POST http://localhost:8080/orders \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;customerId&quot;: &quot;C001&quot;, &quot;items&quot;: [{&quot;productId&quot;: &quot;P001&quot;, &quot;qty&quot;: 2}], &quot;total&quot;: 150.00}&#39; \<br>  | jq .<br><br># Immediate response: status PENDING<br># { &quot;orderId&quot;: &quot;...&quot;, &quot;status&quot;: &quot;PENDING&quot; }<br># After asynchronous processing (&lt; 1s under normal conditions):<br>curl -s http://localhost:8080/orders/{orderId} | jq .status<br># &quot;CONFIRMED&quot;</pre><h3>Failure path</h3><pre># Total exceeds account balance<br>curl -s -X POST http://localhost:8080/orders \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;customerId&quot;: &quot;C001&quot;, &quot;items&quot;: [{&quot;productId&quot;: &quot;P001&quot;, &quot;qty&quot;: 2}], &quot;total&quot;: 999999.00}&#39; \<br>  | jq .orderId<br><br># After compensation:<br>curl -s http://localhost:8080/orders/{orderId} | jq .status<br># &quot;CANCELLED&quot;</pre><h3>What to observe via SQL on ADB</h3><pre>-- Order state over time<br>SELECT id, status, created_at<br>FROM   orders<br>ORDER  BY created_at DESC;<br><br>-- Messages currently in the queue table, with retry count. Replace &lt;queue_table&gt;<br>-- with the value discovered via the USER_QUEUES query in Section 4<br>SELECT msg_id, msg_state, retry_count, user_data<br>FROM   AQ$&lt;queue_table&gt;<br>ORDER  BY enq_time DESC;</pre><p>Adding the orderId to the Logback MDC before publishing each event makes the failure path significantly easier to trace in logs. Not required, but useful from the first test run.</p><h3>What This Covers and What It Does Not</h3><p>The three services above implement a complete choreographed Saga with compensation: order creation, payment debit, inventory reservation, and cancellation on payment failure. The transactional guarantee comes from TxEventQ itself, not from an Outbox relay, an external broker, or a distributed lock.</p><p>What is not covered here: observability. The system runs correctly, but tracing a request that crosses order-service → ORDER_EVENTS → payment-service → PAYMENT_EVENTS → inventory-service requires distributed tracing, and the idempotency gap noted in Section 3 needs a real implementation before this runs unattended in production. Both are natural next steps once the base Saga is in place.</p><h3>References</h3><ul><li>Oracle News, Oracle AI Database 26ai Powers the AI for Data Revolution — <a href="https://www.oracle.com/news/announcement/ai-world-database-26ai-powers-the-ai-for-data-revolution-2025-10-14/">https://www.oracle.com/news/announcement/ai-world-database-26ai-powers-the-ai-for-data-revolution-2025-10-14/</a></li><li>Oracle Developer Guide, Transactional Event Queues Overview — <a href="https://oracle.github.io/microservices-datadriven/transactional-event-queues/">https://oracle.github.io/microservices-datadriven/transactional-event-queues/</a></li><li>OBaaS Docs, Spring Boot Starter for AQ/JMS — <a href="https://oracle.github.io/microservices-datadriven/spring/starters/aqjms/">https://oracle.github.io/microservices-datadriven/spring/starters/aqjms/</a></li><li>Oracle Docs DB 26, Microservices Architecture — <a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/adfns/microservices-architecture.html">https://docs.oracle.com/en/database/oracle/oracle-database/26/adfns/microservices-architecture.html</a></li><li>CloudBank AI, Module 4: Check Processing with JMS + TxEventQ — <a href="https://oracle.github.io/microservices-datadriven/cloudbank/index.html">https://oracle.github.io/microservices-datadriven/cloudbank/index.html</a></li><li>CloudBank AI, Module 5: Saga with LRA — <a href="https://oracle.github.io/microservices-datadriven/cloudbank/saga/prepare/index.html">https://oracle.github.io/microservices-datadriven/cloudbank/saga/prepare/index.html</a></li><li>Oracle Docs, Transactional Event Queues and Advanced Queuing User’s Guide, AQ Views — <a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/adque/aq-messaging-gateway-views.html">https://docs.oracle.com/en/database/oracle/oracle-database/21/adque/aq-messaging-gateway-views.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc86f9ddb4b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle SQL Firewall: Protecting Your Database from Injection in 5 Minutes]]></title>
            <link>https://medium.com/@jefersonferr/oracle-sql-firewall-protecting-your-database-from-injection-in-5-minutes-984b84743815?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/984b84743815</guid>
            <category><![CDATA[oci]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[sql-firewall]]></category>
            <category><![CDATA[autonomous-database]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 14:22:10 GMT</pubDate>
            <atom:updated>2026-06-29T14:22:10.164Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL injection remains one of the most common attack vectors against database-backed applications. Developers add input validation layers, ORMs, and prepared statements — all good practices — but the database itself stays exposed if an attacker finds a path around the application tier.</p><p>Oracle AI Database 26ai ships with SQL Firewall built directly into the kernel. On OCI, it requires no additional license and no separate infrastructure. Every SQL statement is inspected before execution, regardless of whether it arrives over a network connection, a local session, encrypted or clear text, or through PL/SQL.</p><p>This tutorial covers the complete setup: enabling the firewall, capturing normal application behavior, building an allow-list, and enforcing it against an injection attempt.</p><h3>How SQL Firewall Works</h3><p>The model is an allow-list, not a deny-list. You tell the firewall what your application is <em>supposed</em> to do, and it blocks everything else.</p><p>The allow-list has two dimensions:</p><p><strong>SQL statements</strong>: the exact normalized SQL text that the application legitimately executes.</p><p><strong>Session context</strong>: the IP address, OS username, and OS program name from which those statements are allowed to originate. This means that even if an attacker steals a valid database credential, they cannot connect from an unexpected host or client tool and execute arbitrary SQL.</p><p>The workflow is the same in every case: capture, generate allow-list, enforce.</p><h3>Setup</h3><p>You need three roles to manage this feature:</p><ul><li>SQL_FIREWALL_ADMIN — to enable, capture, generate allow-lists, and enforce.</li><li>SQL_FIREWALL_VIEWER — read-only access to firewall views, for monitoring users.</li></ul><p>Create a dedicated firewall admin user and an application user for the demonstration:</p><pre>conn sys/SysPassword1@//localhost:1521/freepdb1 as sysdba<br><br>-- Firewall administrator<br>create user fwadmin identified by &lt;password&gt;;<br>grant create session to fwadmin;<br>grant sql_firewall_admin to fwadmin;<br>-- Application schema<br>create user orders_app identified by &lt;password&gt;;<br>grant create session to orders_app;<br>grant create table to orders_app;<br>grant unlimited tablespace to orders_app;<br>-- Simulate application data<br>create table orders_app.customers (<br>    id     number primary key,<br>    name   varchar2(100),<br>    email  varchar2(200)<br>);<br>insert into orders_app.customers values (1, &#39;Alice&#39;, &#39;alice@example.com&#39;);<br>insert into orders_app.customers values (2, &#39;Bob&#39;,   &#39;bob@example.com&#39;);<br>commit;</pre><h3>Step 1 — Enable the Firewall</h3><p>Connect as the firewall admin and enable the global SQL Firewall:</p><pre>conn fwadmin/fwadmin@//localhost:1521/freepdb1<br><br>exec dbms_sql_firewall.enable;</pre><p>Confirm the status:</p><pre>select status from dba_sql_firewall_status;<br><br>STATUS<br>--------<br>ENABLED</pre><h3>Step 2 — Capture Normal Application Behavior</h3><p>Start a capture session for the application user. The top_level_only =&gt; true parameter tells the firewall to record only top-level SQL statements, not recursive SQL generated internally by the database:</p><pre>begin<br>  dbms_sql_firewall.create_capture(<br>    username       =&gt; &#39;orders_app&#39;,<br>    top_level_only =&gt; true,<br>    start_capture  =&gt; true<br>  );<br>end;<br>/</pre><p>Now simulate normal application activity. Open a separate session as orders_app and execute the queries that your application legitimately runs:</p><pre>conn orders_app/orders_app@//localhost:1521/freepdb1<br><br>-- These are the only queries this user should ever run<br>select id, name, email from orders_app.customers where id = 1;<br>select id, name, email from orders_app.customers where id = 2;</pre><p>Back in the fwadmin session, inspect what was captured:</p><pre>conn fwadmin/fwadmin@//localhost:1521/freepdb1<br><br>select sql_text,<br>       client_program,<br>       os_user,<br>       ip_address<br>from   dba_sql_firewall_capture_logs<br>where  username = &#39;ORDERS_APP&#39;;</pre><p>You will see the normalized SQL text alongside the session context: the IP address, OS user, and client program that originated each statement.</p><p>Stop the capture when you have enough representative activity:</p><pre>exec dbms_sql_firewall.stop_capture(&#39;orders_app&#39;);</pre><h3>Step 3 — Generate and Review the Allow-List</h3><p>Generate the allow-list from the captured activity:</p><pre>exec dbms_sql_firewall.generate_allow_list(&#39;orders_app&#39;);</pre><p>Review what was added across the four allow-list views:</p><pre>-- Allowed SQL statements<br>select username, sql_text<br>from   dba_sql_firewall_allowed_sql<br>where  username = &#39;ORDERS_APP&#39;;<br><br>-- Allowed IP addresses<br>select username, ip_address<br>from   dba_sql_firewall_allowed_ip_addr<br>where  username = &#39;ORDERS_APP&#39;;<br>-- Allowed OS programs<br>select username, os_program<br>from   dba_sql_firewall_allowed_os_prog<br>where  username = &#39;ORDERS_APP&#39;;<br>-- Allowed OS users<br>select username, os_user<br>from   dba_sql_firewall_allowed_os_user<br>where  username = &#39;ORDERS_APP&#39;;</pre><p>If you need to add a SQL statement that was not captured during the learning phase but appears in the violation log, Oracle AI Database 26ai introduced APPEND_ALLOW_LIST_SINGLE_SQL for this purpose. In previous releases, the only option was to import the entire violation log with APPEND_ALLOW_LIST and then manually delete the unwanted entries. With this procedure, you add a single entry directly by its signature:</p><pre>-- First, retrieve the sql_signature from the violation log<br>select sql_signature, sql_text<br>from   dba_sql_firewall_violations<br>where  username = &#39;ORDERS_APP&#39;<br>order  by occurred_at desc;<br><br>-- Then append that specific entry to the allow-list<br>begin<br>  dbms_sql_firewall.append_allow_list_single_sql(<br>    username      =&gt; &#39;orders_app&#39;,<br>    sql_signature =&gt; &#39;&lt;sql_signature_from_violation_log&gt;&#39;,<br>    current_user  =&gt; &#39;ORDERS_APP&#39;,<br>    top_level     =&gt; &#39;Y&#39;,<br>    source        =&gt; dbms_sql_firewall.violation_log<br>  );<br>end;<br>/</pre><h3><strong>Step 4 — Observe Before You Block</strong></h3><p>Before switching to BLOCK mode, run the allow-list in observation mode first. This is especially important in production environments, where a misconfigured allow-list can disrupt legitimate application traffic.</p><pre>begin<br>  dbms_sql_firewall.enable_allow_list(<br>    username =&gt; &#39;orders_app&#39;,<br>    enforce  =&gt; dbms_sql_firewall.enforce_all,<br>    block    =&gt; false<br>  );<br>end;<br>/</pre><p>With block =&gt; false, the firewall logs every violation but allows the statement to execute. Monitor DBA_SQL_FIREWALL_VIOLATIONS for a period that covers all normal application activity — peak hours, batch jobs, scheduled reports:</p><pre>select sql_text,<br>       cause,<br>       ip_address,<br>       os_user,<br>       occurred_at<br>from   dba_sql_firewall_violations<br>where  username = &#39;ORDERS_APP&#39;<br>order  by occurred_at desc;</pre><p>Any legitimate statement appearing here was missed during the capture phase. Add it to the allow-list using APPEND_ALLOW_LIST_SINGLE_SQL before enabling blocking. Only when the violation log stays clean under normal load should you proceed to BLOCK mode.</p><h3>Step 5— Enforce the Allow-List</h3><p>Enable enforcement in BLOCK mode. The enforce parameter controls what is validated: ENFORCE_SQL checks only the SQL text, ENFORCE_CONTEXT checks only the session context (IP address, OS user, and client program), and ENFORCE_ALL activates both simultaneously. The block parameter determines whether violations are blocked or only logged:</p><pre>begin<br>  dbms_sql_firewall.enable_allow_list(<br>    username        =&gt; &#39;orders_app&#39;,<br>    enforce         =&gt; dbms_sql_firewall.enforce_all,<br>    block           =&gt; true<br>  );<br>end;<br>/</pre><h3>Step 6— Attempt a SQL Injection</h3><p>Now simulate an injection. Open a session as orders_app and try to inject additional SQL via a crafted input that the application should never produce:</p><pre>conn orders_app/orders_app@//localhost:1521/freepdb1<br><br>-- This is what a legitimate application query looks like<br>select id, name, email from orders_app.customers where id = 1;<br>-- This is what an injected query looks like<br>select id, name, email from orders_app.customers where id = 1 or 1=1;</pre><p>The injected query returns an error immediately:</p><pre>ORA-47605: SQL Firewall violation</pre><p>The database never evaluated the query. The firewall blocked it before execution because the normalized SQL text does not match any entry in the allow-list.</p><p>Note that a SQL text violation raises ORA-47605 but keeps the session alive. A context violation — connecting from an unexpected IP address or client program — terminates the connection entirely.</p><p>Check the violation log:</p><pre>conn fwadmin/fwadmin@//localhost:1521/freepdb1<br><br>select username,<br>       sql_text,<br>       ip_address,<br>       os_user,<br>       client_program,<br>       occurred_at<br>from   dba_sql_firewall_violations<br>where  username = &#39;ORDERS_APP&#39;<br>order  by occurred_at desc;</pre><p>Every blocked attempt is logged with the full context: the exact SQL text, the originating IP address, the OS user, and the timestamp. On OCI, this log integrates with Oracle Data Safe for centralized monitoring across multiple databases.</p><h3>Context Enforcement in Practice</h3><p>Consider a case where the database credential is stolen and used from an unexpected host:</p><pre>conn fwadmin/fwadmin@//localhost:1521/freepdb1<br><br>-- Check which IPs are allowed<br>select username, ip_address<br>from   dba_sql_firewall_allowed_ip_addr<br>where  username = &#39;ORDERS_APP&#39;;</pre><p>If orders_app connects from an IP address not in the allow-list — even with the correct password and a perfectly valid SQL statement — the connection is blocked. The violation log records it as a context violation rather than a SQL violation, making it easy to distinguish between injection attempts and suspicious lateral movement.</p><h3>Recovery: What to Do When You Block Yourself</h3><p>If a legitimate query is incorrectly blocked, do not disable the firewall. Use APPEND_ALLOW_LIST to add the specific violation to the allow-list:</p><pre>begin<br>  dbms_sql_firewall.append_allow_list(<br>    username    =&gt; &#39;orders_app&#39;,<br>    source      =&gt; dbms_sql_firewall.ALL_LOGS<br>  );<br>end;<br>/</pre><p>If you need to temporarily disable enforcement for a user during a deployment that introduces new queries, disable only that user’s allow-list:</p><pre>exec dbms_sql_firewall.disable_allow_list(&#39;orders_app&#39;);</pre><p>Run a new capture to absorb the new queries, regenerate the allow-list, and re-enable enforcement. The firewall itself stays enabled for all other users throughout the process.</p><h3>Licensing</h3><p>SQL Firewall is included in Oracle AI Database 26ai at no additional cost on Oracle Cloud Infrastructure (Autonomous Database, Base Database Service, Exadata Cloud Service). For on-premises Enterprise Edition, it requires the Database Security option or the Oracle Database Vault license. The Free Edition of Oracle AI Database 26ai includes SQL Firewall for testing and development.</p><h3>What Changes With 26ai</h3><p>In Oracle Database 23ai, SQL Firewall was available but required separate enablement. Starting with 26ai, it is built into the kernel and cannot be bypassed regardless of the connection path. The 26ai release also added APPEND_ALLOW_LIST_SINGLE_SQL, which significantly improves the operational workflow for tuning allow-lists after violations — previously you had to append the entire violation log and then manually delete unwanted entries.</p><h3>Key Views Reference</h3><p>View Description dba_sql_firewall_status Global firewall status dba_sql_firewall_capture_logs SQL and context captured during learning phase dba_sql_firewall_allowed_sql SQL statements in the allow-list dba_sql_firewall_allowed_ip_addr Allowed IP addresses per user dba_sql_firewall_allowed_os_prog Allowed client programs per user dba_sql_firewall_allowed_os_user Allowed OS users per user dba_sql_firewall_violations Log of all blocked attempts</p><h3>Closing Thoughts</h3><p>SQL Firewall does not replace prepared statements or input validation at the application layer. It complements them. The value is that it operates at a layer no application-side control can reach: inside the database kernel, after the network stack, before the SQL engine. An attacker who compromises the application server, steals a service account credential, or finds a path that bypasses the application entirely is still blocked at the database kernel, before any SQL reaches the execution engine.</p><p>For a single user, the setup takes minutes: enable, capture, generate, enforce. The ongoing work is keeping allow-lists accurate as the application evolves — and APPEND_ALLOW_LIST_SINGLE_SQL in 26ai removes what was previously a two-step manual process.</p><p><strong>References</strong></p><ul><li>Oracle AI Database SQL Firewall User’s Guide — <a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/sqlfw/">https://docs.oracle.com/en/database/oracle/oracle-database/26/sqlfw/</a></li><li>Oracle AI Database 26ai New Features Guide — <a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/nfcoa/">https://docs.oracle.com/en/database/oracle/oracle-database/26/nfcoa/</a></li><li>SQL Firewall in Oracle Database 23ai/26ai (oracle-base.com) — <a href="https://oracle-base.com/articles/23/sql-firewall-23">https://oracle-base.com/articles/23/sql-firewall-23</a></li><li>Oracle Data Safe: SQL Firewall Overview — <a href="https://docs.oracle.com/en/cloud/paas/data-safe/udscs/sql-firewall-overview.html">https://docs.oracle.com/en/cloud/paas/data-safe/udscs/sql-firewall-overview.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=984b84743815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running a ReAct Agent Inside Oracle Autonomous AI Database 26ai from a Spring Boot BPMN Runtime]]></title>
            <link>https://medium.com/@jefersonferr/running-a-react-agent-inside-oracle-autonomous-ai-database-26ai-from-a-spring-boot-bpmn-runtime-4dcf91aa8c02?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dcf91aa8c02</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[oracle-autonomous-db]]></category>
            <category><![CDATA[bpmn]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 19:21:38 GMT</pubDate>
            <atom:updated>2026-06-20T19:21:38.860Z</atom:updated>
            <content:encoded><![CDATA[<p><em>BPMNFlow dispatched API calls through fixed parameter mappings in Java and PL/SQL handlers. This article adds a third path: a ReAct agent inside the database that reasons about the process context before making the call.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3A2sO6XwWVuewApDKvdjAg.png" /></figure><p>This is the third article in the BPMNFlow series. The <a href="https://medium.com/@jefersonferr/a-practical-look-at-oracle-json-duality-views-in-a-real-spring-boot-app-27c11921d328">first</a> evaluated Oracle JSON Relational Duality Views against BPMNFlow’s 17-table persistence model. The <a href="https://medium.com/@jefersonferr/optimistic-concurrency-in-spring-boot-oracle-duality-view-etags-vs-jpa-version-ecbcfc90b8cb">second</a> compared ETag-based optimistic concurrency from Duality Views against JPA @Version. Both focused on the persistence layer of <a href="https://github.com/jefersonferr/bpmnflow-process-runtime-oracle">bpmnflow-process-runtime-oracle</a>.</p><p>The project already had two mechanisms for this. A Java handler resolves placeholder variables from the process instance and dispatches the call through RestTemplate. A PL/SQL handler does the same inside the database using DBMS_CLOUD.SEND_REQUEST. Both work. Both are deterministic: the parameter mapping is fixed at design time, the call goes out, the response comes back.</p><p>What neither of them can do is reason. If a process instance has multiple candidate variables for a parameter, the handler uses whichever one matches the placeholder pattern. It does not evaluate context. It does not adapt to the state of the running instance. It executes the mapping that was written into the process model.</p><p>Oracle Autonomous AI Database 26ai changes what is possible here. The MCP Server embedded in the database, combined with the Select AI Agent framework, makes it possible to invoke a ReAct agent directly from a JDBC connection: an agent that reasons about the process context, decides how to construct the call, and returns a structured response that the runtime maps back into the instance.</p><p>The process model does not change. The API activity declaration in the .bpmn file is the same. What changes is what happens inside the database when that activity fires.</p><h4>What the MCP Server Embedded in ADB 26ai Actually Is</h4><p>The Oracle Autonomous Database MCP Server is not just a connectivity layer. When you enable it on an ADB instance, the database activates a managed, multi-tenant agent runtime that runs inside the same environment as your data, your PL/SQL, and your security policies. The HTTP endpoint that Claude Desktop or an OCI AI Agent connects to is the surface; the substance is the agent infrastructure underneath it.</p><p><strong>The MCP Server</strong> is the protocol layer. It exposes an HTTPS endpoint that any MCP-compatible client (Claude Desktop, OCI ADK, a custom Python application) can connect to. As <a href="https://blogs.oracle.com/database/gain-agentic-access-to-any-oracle-database-in-the-cloud-with-native-enterprise-grade-managed-mcp-servers-in-oci">Jeff Smith and Kris Rice describe in the Oracle Database blog</a>, this extends across the Oracle database estate in OCI, including deployments on AWS, Azure, and Google Cloud. Authentication uses OAuth or short-lived bearer tokens. The tools you register with DBMS_CLOUD_AI_AGENT are what the MCP clients discover and invoke.</p><p><strong>Select AI Agent</strong> is the reasoning engine. It implements the ReAct (Reasoning and Acting) pattern inside the database: the agent receives a prompt and iterates (reasoning, executing a tool, observing the result) until it produces a final answer. Existing SQL and stored procedures become agent-callable tools without a REST wrapper, the same Select AI Agent framework that <a href="https://blogs.oracle.com/machinelearning/build-ai-agents-using-oci-agent-developer-kit-with-oracle-autonomous-ai-database-mcp-server">Chandrakanth Putha demonstrates with OCI ADK in the Oracle Machine Learning blog</a>.</p><p>What makes this relevant for a BPMN runtime is that the agent does not have to be invoked over HTTP. DBMS_CLOUD_AI_AGENT.RUN_TEAM is a PL/SQL function. A Spring Boot application with a JDBC connection can call it directly, invoking the same reasoning engine that a Claude Desktop client would reach via the MCP endpoint. The protocol transport is a detail; the agent is the same.</p><p>Governance matters as much as connectivity for enterprise adoption. As <a href="https://blogs.oracle.com/developers/managed-mcp-in-autonomous-ai-database-remote-governed-tools-per-database">Mark Nelson’s article on managed MCP</a> lays out, every tool invocation runs under a real database identity, subject to existing VPD policies, network ACLs, and Unified Auditing. The agent inherits the trust model of the database. There is no separate trust stack to build.</p><h4>The Broader Oracle MCP Ecosystem</h4><p>The McpApiHandlerProvider is one integration point in a larger ecosystem that Oracle has been building out rapidly. Understanding where it fits clarifies why invoking RUN_TEAM via JDBC from a Spring Boot application is architecturally coherent, not a workaround.</p><p>The <a href="https://blogs.oracle.com/database/gain-agentic-access-to-any-oracle-database-in-the-cloud-with-native-enterprise-grade-managed-mcp-servers-in-oci">OCI Managed MCP Service</a> extends the same tool registry to any Oracle database in OCI (Autonomous, Base Database, Exadata) with OCI identity controls, SQL Reports for governed parameterized queries, and no incremental service charge. The <a href="https://www.ateam-oracle.com/integrate-oracle-fusion-ai-agent-studio-with-autonomous-db-mcp-server">Fusion AI Agent Studio integration</a> uses the same MCP endpoint to make ADB tools available inside Oracle Fusion agentic workflows without REST wrapper.</p><p>The common primitive across all of these is DBMS_CLOUD_AI_AGENT.CREATE_TOOL. Regardless of the client (Claude Desktop over HTTP, an OCI ADK agent, a Fusion workflow, or a Spring Boot JDBC caller), the tool definition in the database is the same object. Governance, auditing, and network policy travel with the tool, not with the client that invokes it.</p><h4>The Pipeline: From BPMN Activity to Agent to REST API</h4><p>BPMNFlow uses an ApiHandlerProvider interface. When the runtime reaches an API activity in a process instance, it resolves the active provider and calls execute(ApiHandlerContext) → Map&lt;String, String&gt;. Placeholder resolution and output mapping always stay in Java. The provider handles the transport.</p><p>The McpApiHandlerProvider added to bpmnflow-process-runtime-oracle implements this interface by invoking a Select AI Agent team via JDBC. The full pipeline:</p><pre>Spring Boot (McpApiHandlerProvider)<br>  └─ JDBC → DBMS_CLOUD_AI.CREATE_CONVERSATION()<br>  └─ JDBC → DBMS_CLOUD_AI_AGENT.RUN_TEAM<br>       └─ BPMNFLOW_AGENT (ReAct, enable_human_tool: False)<br>            └─ BPMNFLOW_API_TASK (instruction: call exactly once)<br>                 └─ BPMNFLOW_API_CALLER (tool)<br>                      └─ BPMNFLOW_MCP_CALL_API (PL/SQL)<br>                           └─ DBMS_CLOUD.SEND_REQUEST → REST API</pre><p>The activity declaration in the .bpmn file:</p><pre>&lt;bpmnflow:apiHandler&gt;<br>  &lt;bpmnflow:property name=&quot;connector.input.url&quot;<br>    value=&quot;https://api.example.com/v1/authorize&quot;/&gt;<br>  &lt;bpmnflow:property name=&quot;connector.input.method&quot; value=&quot;POST&quot;/&gt;<br>  &lt;bpmnflow:property name=&quot;connector.input.payload&quot;<br>    value=&quot;${payloadBuilder.build(cliente_id, valor_total)}&quot;/&gt;<br>  &lt;bpmnflow:property name=&quot;connector.output.pagamento_status&quot; value=&quot;status&quot;/&gt;<br>  &lt;bpmnflow:property name=&quot;connector.output.pagamento_txn_id&quot; value=&quot;txn_id&quot;/&gt;<br>&lt;/bpmnflow:apiHandler&gt;</pre><p>The connector.output.* values are field names the agent&#39;s JSON response must contain. The runtime uses JsonNode.get(variableName) to extract them, following the same pattern as the PL/SQL handler. The process model does not need to know which handler executed.</p><h4>Setting Up the Agent Pipeline in ADB 26ai</h4><p>Five database objects compose the pipeline. Each one has a distinct role, and several behaviors only become clear when running the feature against a real workload: some absent from the official documentation entirely, others documented in examples but not in error paths.</p><p><strong>OCI Credential</strong></p><p>The agent needs to reach OCI GenAI to run the LLM. DBMS_CLOUD.CREATE_CREDENTIAL creates the credential using an OCI API Key. The private key must be provided as pure Base64 — no -----BEGIN PRIVATE KEY----- or -----END PRIVATE KEY----- lines, no line breaks:</p><pre>grep -v &quot;BEGIN\|END&quot; ~/.oci/oci_api_key.pem | tr -d &#39;\n&#39;</pre><p>ORA-20401 (Authorization failed) means the fingerprint or the key body is wrong. A separate trap: oci_endpoint is not a valid attribute for the oci provider in CREATE_PROFILE. It causes ORA-20046. It appears in several community examples and is incorrect.</p><p><strong>AI Profile</strong></p><p>The profile connects the agent to OCI GenAI with the compartment OCID. Validate it independently with DBMS_CLOUD_AI.GENERATE before wiring it into the agent pipeline.</p><p><strong>PL/SQL Function: </strong><strong>BPMNFLOW_MCP_CALL_API</strong></p><p>This is the function the agent calls when it executes the HTTP request. It uses DBMS_CLOUD.SEND_REQUEST with credential_name =&gt; NULL, which means Instance Principal authentication, which requires no network ACL, unlike UTL_HTTP.</p><p><strong>Tool: </strong><strong>BPMNFLOW_API_CALLER</strong></p><p>The tool registers the function as an agent capability. Here is where the first significant undocumented behavior appears: tool_type: PLSQL does not exist in the API. Using it causes ORA-20052. The correct syntax uses instruction, function, and tool_inputs, with no tool_type attribute:</p><pre>DBMS_CLOUD_AI_AGENT.CREATE_TOOL(<br>  tool_name  =&gt; &#39;BPMNFLOW_API_CALLER&#39;,<br>  attributes =&gt; &#39;{<br>    &quot;instruction&quot;:  &quot;Executes an HTTP REST API call and returns the response body as JSON.&quot;,<br>    &quot;function&quot;:     &quot;BPMNFLOW_MCP_CALL_API&quot;,<br>    &quot;tool_inputs&quot;:  [<br>      {&quot;name&quot;: &quot;P_ENDPOINT&quot;, &quot;description&quot;: &quot;Full URL of the REST endpoint&quot;},<br>      {&quot;name&quot;: &quot;P_METHOD&quot;,   &quot;description&quot;: &quot;HTTP method: GET, POST, PUT, PATCH, DELETE&quot;},<br>      {&quot;name&quot;: &quot;P_PAYLOAD&quot;,  &quot;description&quot;: &quot;JSON request body, or empty string for GET&quot;}<br>    ]<br>  }&#39;<br>);</pre><p>The <a href="https://www.ateam-oracle.com/integrate-oracle-fusion-ai-agent-studio-with-autonomous-db-mcp-server">A-Team article on Fusion AI Agent Studio integration</a> shows the same CREATE_TOOL pattern for a sales analytics function on the SH sample schema. The tool definition is identical regardless of which MCP client will invoke it: Claude Desktop, OCI ADK, or a JDBC caller.</p><p><strong>Agent, Task, and Team</strong></p><p>The agent carries the LLM configuration and the enable_human_tool: False flag that prevents indefinite blocking in a headless runtime. The task instruction controls execution scope. Together they run in sequential topology inside the team.</p><p>To verify the setup, the catalog views are user_ai_agent_tools, user_ai_agents, user_ai_agent_tasks, and user_ai_agent_teams. All plural. The team view uses column agent_team_name, not team_name.</p><h4>The Conversation Lifecycle: A Non-Obvious Constraint</h4><p>DBMS_CLOUD_AI_AGENT.RUN_TEAM requires a conversation_id obtained from Oracle via DBMS_CLOUD_AI.CREATE_CONVERSATION(). The official documentation shows this pattern in examples but does not describe what happens when a caller tries to work around it. Passing params =&gt; NULL causes ORA-01400: the internal conversation table has a NOT NULL constraint. Generating a UUID in Java and passing it causes ORA-20050 (conversation does not exist). The ID cannot come from the caller.</p><p><strong>In PL/SQL:</strong></p><pre>v_conv_id := DBMS_CLOUD_AI.CREATE_CONVERSATION();<br>v_result  := DBMS_CLOUD_AI_AGENT.RUN_TEAM(<br>  team_name   =&gt; &#39;BPMNFLOW_TEAM&#39;,<br>  user_prompt =&gt; :prompt,<br>  params      =&gt; JSON_OBJECT(&#39;conversation_id&#39; VALUE v_conv_id)<br>);</pre><p>In the McpApiHandlerProvider, this requires two CallableStatement executions on the same JDBC connection:</p><pre>// Step 1 — obtain a valid conversation ID from Oracle<br>try (CallableStatement cs = conn.prepareCall(<br>    &quot;BEGIN ? := DBMS_CLOUD_AI.CREATE_CONVERSATION(); END;&quot;)) {<br>  cs.registerOutParameter(1, Types.VARCHAR);<br>  cs.execute();<br>  conversationId = cs.getString(1);<br>}<br><br>// Step 2 — invoke the agent team<br>try (CallableStatement cs = conn.prepareCall(RUN_TEAM_SQL)) {<br>  // conversationId bound into params JSON<br>  cs.execute();<br>}</pre><p>Each BPMN activity invocation creates and discards its own conversation.</p><h4>Controlling the ReAct Loop</h4><p>The ReAct pattern (think, act, observe, repeat) is what makes the agent useful for open-ended reasoning tasks. In a BPMN activity execution with a fixed contract, it is a liability if left unconstrained.</p><p>During implementation, a prompt phrased as an analytical request triggered 104 tool invocations over 12 minutes. The agent kept refining its interpretation of the process context, each observation producing a new reasoning step rather than terminating. This is correct ReAct behavior for an open-ended task. It is not acceptable for a runtime activity that needs to complete in under 15 seconds.</p><p>The fix operates at two levels. The first is the enable_human_tool: False flag on the agent, which prevents the blocking WAITING_FOR_HUMAN state. The second is the task instruction itself:</p><blockquote>Call the tool BPMNFLOW_API_CALLER exactly once using the endpoint, method, and payload provided. After receiving the tool result, immediately return a single valid JSON object containing only the output field values. Do not call the tool again. Do not explain. Do not use markdown or code blocks.</blockquote><p>The McpPromptBuilder generates the prompt for each activity invocation. For a payment authorization activity:</p><pre>Execute the following API call for BPMN activity &#39;SC-PMT_AUTH&#39; (instance: 51409):<br><br>- endpoint: https://api.example.com/v1/authorize<br>- method:   POST<br>- payload:  {&quot;customer_id&quot;:&quot;12345&quot;,&quot;amount&quot;:&quot;100.00&quot;,&quot;currency&quot;:&quot;BRL&quot;}<br><br>Process variables (for reference):<br>- cliente_id: 12345<br>- valor_total: 100.00<br><br>Call the tool exactly once using the endpoint, method and payload above.<br>After receiving the tool result, immediately return a single valid JSON object<br>containing only the output field values.<br>Do not call the tool again. Do not explain. Do not use markdown or code blocks.</pre><p>Two decisions in this prompt deserve explanation. The verb is “Execute”, not “Analyze”: imperative form closes the reasoning space that analytical framing opens. Process variables appear under “for reference” rather than as direct parameters, available to the agent if needed, but not an invitation to derive alternative mappings from them.</p><h4>Parsing the Response Envelope</h4><p>The agent executes, the tool completes, the agent produces its answer. What arrives at the Java layer is not clean JSON.</p><p>Oracle wraps the agent output in an envelope with this shape:</p><pre>{ &quot;status&quot;:&quot;success&quot;,<br>  &quot;result&quot;:&quot;{\n  \&quot;pagamento_status\&quot;: \&quot;approved\&quot;,\n  \&quot;pagamento_txn_id\&quot;: \&quot;TXN-98765\&quot;\n}\n&quot;}</pre><p>The result field contains the actual JSON, but with literal newline characters embedded inside the string value. This violates RFC 7159. The standard Jackson ObjectMapper rejects it without raising a clear error.</p><p>The McpAgentResponse parser uses three steps:</p><pre>// Step 1 — lenient outer parse tolerating embedded control chars<br>ObjectMapper lenient = objectMapper.copy()<br>    .enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);<br>JsonNode outer = lenient.readTree(agentText);<br><br>// Step 2 — unwrap the envelope and sanitize newlines<br>String innerJson = outer.get(&quot;result&quot;).asText()<br>    .replace(&quot;\n&quot;, &quot; &quot;).replace(&quot;\r&quot;, &quot; &quot;).trim();<br><br>// Step 3 — strict inner parse<br>JsonNode inner = objectMapper.readTree(innerJson);</pre><p>The lenient mapper handles the outer envelope. Sanitizing the string before the second parse avoids re-encountering the control character problem in the inner JSON. A brace-balancing fallback handles edge cases where the agent includes text before or after the JSON object, which happens when the task instruction is not tight enough.</p><p>After parsing, output mapping uses JsonNode.get(variableName) where variableName comes from the connector.output.* property values in the BPMN file. The output mapping pattern is identical to the PL/SQL handler; the runtime does not need to know which provider executed.</p><h4>Validation Results</h4><p>Two activities on the pizza-delivery process model validated end-to-end:</p><pre>INFO McpApiHandlerProvider : <br>  Invoking RUN_TEAM &#39;BPMNFLOW_TEAM&#39; for &#39;SC-PMT_AUTH&#39; (instance=51409)<br>INFO McpApiHandlerProvider : <br>  RUN_TEAM completed for activity &#39;SC-PMT_AUTH&#39; (instance=51409)<br>INFO ApiHandlerExecutor     : <br>  API activity &#39;SC-PMT_AUTH&#39; completed — 3 variable(s) persisted<br>INFO ProcessInstanceService : <br>  Instance 51409 advanced &#39;SC-PMT_AUTH&#39; -&gt; &#39;SC-RCV&#39;<br><br>INFO McpApiHandlerProvider : <br>  Invoking RUN_TEAM &#39;BPMNFLOW_TEAM&#39; for &#39;DL-TRK_CREATE&#39; (instance=51409)<br>INFO McpApiHandlerProvider : <br>  RUN_TEAM completed for activity &#39;DL-TRK_CREATE&#39; (instance=51409)<br>INFO ApiHandlerExecutor     : <br>  API activity &#39;DL-TRK_CREATE&#39; completed — 3 variable(s) persisted</pre><p>DL-TRK_CREATE persisted driver_name, estimated_delivery_time, and tracking_id.</p><p>Latency per invocation ranged from 5 to 15 seconds, the cost of the LLM round-trip through OCI GenAI including agent reasoning, tool execution, and response composition. The Java and PL/SQL handlers complete the same activity in under a second. That gap is the cost of contextual reasoning: acceptable for activities where fixed parameter mappings are not enough, and a poor fit for everything else.</p><p>The decision is not about capability. It is about what the activity actually needs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1uQU2YIoblZc_zI1_x-9w.png" /><figcaption>Table 1 — Use the Java handler as the default. Switch to PL/SQL for Oracle legacy systems. Reserve the MCP handler for activities where contextual reasoning justifies the latency and token cost.</figcaption></figure><h4>Conclusion</h4><p>Oracle Autonomous AI Database 26ai does not just store data, it runs agents. The MCP Server embedded in the database, combined with the Select AI Agent framework, makes it possible to invoke ReAct reasoning directly from a JDBC connection, governed by the same security model that protects the data itself.</p><p>The McpApiHandlerProvider in <a href="https://github.com/jefersonferr/bpmnflow-process-runtime-oracle">bpmnflow-process-runtime-oracle</a> puts that capability to work inside a real BPMN runtime. The process model declares what to call. The agent decides how. The Java layer maps the result back into the process instance. Each layer owns exactly what it should.</p><p>The behaviors surfaced here — the error paths around CREATE_CONVERSATION, the tool_type: PLSQL trap, the response envelope with embedded newlines, and the loop dynamics of an unconstrained ReAct prompt — are the kind of detail that only emerges from running the feature against a real workload, not from reading the documentation alone.</p><p>The full implementation is available at <a href="https://github.com/jefersonferr/bpmnflow-process-runtime-oracle">github.com/jefersonferr/bpmnflow-process-runtime-oracle</a>.</p><h3>References</h3><ul><li>Smith, J., Rice, K. (2026). <em>Gain Agentic Access to Any Oracle Database in the Cloud with Native, Enterprise-grade Managed MCP Servers in OCI</em>. Oracle Database Insider Blog. <a href="https://blogs.oracle.com/database/gain-agentic-access-to-any-oracle-database-in-the-cloud-with-native-enterprise-grade-managed-mcp-servers-in-oci">https://blogs.oracle.com/database/gain-agentic-access-to-any-oracle-database-in-the-cloud-with-native-enterprise-grade-managed-mcp-servers-in-oci</a></li><li>Nelson, M. (2026). <em>Managed MCP in Autonomous AI Database: remote, governed tools per database</em>. Oracle Developers Blog. <a href="https://blogs.oracle.com/developers/managed-mcp-in-autonomous-ai-database-remote-governed-tools-per-database">https://blogs.oracle.com/developers/managed-mcp-in-autonomous-ai-database-remote-governed-tools-per-database</a></li><li>Putha, C. (2026). <em>Build AI Agents using OCI Agent Developer Kit with Oracle Autonomous AI Database MCP Server</em>. Oracle Machine Learning Blog. <a href="https://blogs.oracle.com/machinelearning/build-ai-agents-using-oci-agent-developer-kit-with-oracle-autonomous-ai-database-mcp-server">https://blogs.oracle.com/machinelearning/build-ai-agents-using-oci-agent-developer-kit-with-oracle-autonomous-ai-database-mcp-server</a></li><li>Mathew, R., Nolan, S. (2026). <em>Integrate Oracle Fusion AI Agent Studio with Autonomous DB MCP Server</em>. Oracle A-Team Chronicles. <a href="https://www.ateam-oracle.com/integrate-oracle-fusion-ai-agent-studio-with-autonomous-db-mcp-server">https://www.ateam-oracle.com/integrate-oracle-fusion-ai-agent-studio-with-autonomous-db-mcp-server</a></li></ul><p>Tags: oracle · autonomous-database · mcp · select-ai · bpmn · spring-boot · genai · react-agent · oracle-ace</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dcf91aa8c02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimistic Concurrency in Spring Boot: Oracle Duality View ETags vs. JPA @Version]]></title>
            <link>https://medium.com/@jefersonferr/optimistic-concurrency-in-spring-boot-oracle-duality-view-etags-vs-jpa-version-ecbcfc90b8cb?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecbcfc90b8cb</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oracle-json-duality-views]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Sun, 17 May 2026 02:51:07 GMT</pubDate>
            <atom:updated>2026-05-17T02:51:07.296Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 2 of the BPMNFlow + Oracle JSON Relational Duality Views series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-2HmZ79CQ0uuWCx9jGbyw.png" /></figure><p>In <a href="https://medium.com/@jefersonferr/a-practical-look-at-oracle-json-duality-views-in-a-real-spring-boot-app-27c11921d328">Part 1</a>, we replaced four JPA entity classes and several JOIN FETCH queries with a single JSON Relational Duality View, a feature introduced in Oracle 23ai that exposes relational data as readable and writable JSON documents. The read path got simpler, writes got faster, and at the bottom of the WfProcessInstanceDoc record there was a field declared as Object with a Javadoc that said <em>&quot;used for ETag-based OCC&quot;</em>:</p><pre>/** <br> * Oracle injects _metadata into every Duality View document.<br> * Contains the ETag used for optimistic concurrency control.<br> * Preserved as Object for round-trip serialization.<br> */<br>@JsonProperty(&quot;_metadata&quot;)<br>private Object metadata;</pre><p>In Part 1, we annotated the class with @JsonIgnoreProperties(ignoreUnknown = true) and moved on. Andy Tael did the same in his Spring Boot recipe tutorial. Simon Martinelli tried to map _metadata to a typed class using the Oracle JSONB starter, hit a deserialization bug in the driver, and opened <a href="https://github.com/oracle/spring-cloud-oracle/issues/164">GitHub Issue #164</a>. Most tutorials treat _metadata as noise that the application should discard.</p><p>This article covers what happens when you keep it instead.</p><h3>Lost Updates in a Stateless REST API</h3><p>A sequential process does not imply a single writer. In a real deployment, a CRM system and an ERP system might both call PUT /workflow/{id}/variables at the same time. Both read the same instance state. Both modify a variable locally. Both send their update back.</p><pre>System A: GET /workflow/51305 → { lastUpdater: &quot;crm&quot;,  status: &quot;PROCESSING&quot; }<br>System B: GET /workflow/51305 → { lastUpdater: &quot;erp&quot;,  status: &quot;PROCESSING&quot; }<br><br>System A: PUT /workflow/51305/variables → 200 OK (sets lastUpdater = &quot;crm-approved&quot;)<br>System B: PUT /workflow/51305/variables → 200 OK (sets lastUpdater = &quot;erp-rejected&quot;)</pre><p>Both return 200. System A’s update was silently overwritten. The variable now says “erp-rejected” and there is no error, no log entry, no indication that anything went wrong. This is the lost update problem, and in a stateless REST API it is invisible to the client without explicit concurrency control.</p><p>Our benchmark made the consequence concrete. Ten workers, no OCC, all return 200:</p><pre>JPA_NOCC — 10 workers:<br>  successes: 10, conflicts: 0<br>  last_updater: &quot;worker-4&quot; ← 9 workers wrote data that was overwritten</pre><p>Nine workers wrote data that was overwritten, with no error returned to any of them.</p><h3>What _metadata Contains</h3><p>Every document returned by a Duality View includes a _metadata field:</p><pre>{<br>  &quot;_id&quot;: 51305,<br>  &quot;_metadata&quot;: {<br>    &quot;etag&quot;: &quot;A3F8B2C1D4E5F6A7B8C9D0E1F2A3B4C5&quot;,<br>    &quot;asof&quot;: &quot;00000000008B03CD&quot;<br>  },<br>  &quot;instanceStatus&quot;: &quot;ACTIVE&quot;,<br>  &quot;variables&quot;: [...]<br>}</pre><p>The etag value is a hash Oracle computes over the entire document — every row from every table that participates in the Duality View. Not just wf_process_instance. Not just the row that was most recently modified. Every column of every joined table contributes to the hash.</p><p>The asof field records the document&#39;s SCN — System Change Number — as a zero-padded hexadecimal string: Oracle&#39;s internal logical clock, a monotonically increasing counter that advances with each committed transaction. It plays no role in OCC; its use is cross-document consistency, allowing a client to query other views or tables AS OF SCN at the exact moment a given document was fetched. Like etag, it is managed entirely by Oracle and ignored on INSERT and UPDATE.</p><p>When an UPDATE includes this _metadata back to the database, Oracle recomputes the ETag over the current state of all participating rows and compares it against the value in the payload. If they differ, Oracle rejects the write immediately, no row lock was acquired at read time, no session was blocked waiting. Two distinct errors can surface: ORA-42699 (<em>&quot;The ETAG of document with ID &#39;...&#39; in the database did not match the ETAG passed in&quot;</em>) when the client supplied an explicit ETag that no longer matches the current state; and ORA-40896 (<em>&quot;Concurrent modification detected&quot;</em>) when Oracle detects the conflict through its internal round-trip validation, the path taken when buildMetadataForWrite embeds the _metadata fetched at read time but no explicit If-Match was sent by the client. Both codes map to the same root cause and the repository catches both. As Martin Carsten Bach described in his February 2026 writeup, the response is direct rather than waiting for an enqueue. The Oracle documentation calls this value-based or lock-free concurrency control.</p><h3>The Duality View Implementation</h3><p>The Duality View path already read _metadata as part of every document fetch. What was missing was the HTTP layer: emitting ETag on GET responses and reading If-Match on PUT requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*s1cn4e69A_IEwxPa486KVQ.png" /><figcaption>Figure 1 — ETag-based OCC: the client receives the ETag on GET and presents it on PUT. Oracle recomputes the hash and either commits (200) or rejects without acquiring any row lock (412).</figcaption></figure><p><strong>ProcessController</strong> needed two header changes:</p><pre>// GET /workflow/{id}<br>@GetMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;ProcessInstanceResponse&gt; getInstance(@PathVariable Long id) {<br>    WfProcessInstanceDoc doc = dualityService.getInstanceDoc(id);<br>    String etag = doc.etagValue();  // extracts hash from _metadata<br>    return ResponseEntity.ok()<br>            .eTag(etag)<br>            .body(dualityService.buildResponseFromDoc(doc));<br>}<br><br>// PUT /workflow/{id}/variables<br>@PutMapping(&quot;/{id}/variables&quot;)<br>public ResponseEntity&lt;?&gt; setVariables(<br>        @PathVariable Long id,<br>        @RequestHeader(value = &quot;If-Match&quot;, required = false) String ifMatch,<br>        @RequestBody List&lt;VariableRequest&gt; variables) {<br>    String clientEtag = unquote(ifMatch);<br>    return ResponseEntity.ok(dualityService.setVariables(id, clientEtag, variables));<br>}</pre><p><strong>ProcessInstanceDualityService</strong> passes the client ETag through to the repository:</p><pre>public List&lt;VariableResponse&gt; setVariables(Long instanceId,<br>                                            String clientEtag,<br>                                            List&lt;VariableRequest&gt; variables) {<br>    WfProcessInstanceDoc doc = dualityRepo.findById(instanceId);<br>    WfProcessInstanceDoc updated = mergeVariables(doc, variables);<br><br>    // buildMetadataForWrite embeds clientEtag in the _metadata sent to Oracle.<br>    // If clientEtag is present and stale, Oracle raises ORA-42699 → HTTP 412.<br>    // If clientEtag is null, Oracle still validates the round-trip hash.<br>    Object metadataToWrite = buildMetadataForWrite(doc.metadata(), clientEtag);<br>    WfProcessInstanceDoc withMeta = updated.withMetadata(metadataToWrite);<br><br>    dualityRepo.update(withMeta, instanceId);<br>    return buildVariableResponse(instanceId);<br>}</pre><p><strong>WfProcessInstanceDualityRepository</strong> translates the Oracle error into a typed exception:</p><pre>public WfProcessInstanceDoc update(WfProcessInstanceDoc doc, Long instanceId) {<br>    try {<br>        jdbcTemplate.update(UPDATE_SQL, serialize(doc), instanceId);<br>        return findById(instanceId);<br>    } catch (UncategorizedSQLException e) {<br>        int code = extractOracleCode(e);<br>        if (code == 40896 || code == 42699) {<br>            throw new ETagConflictException(instanceId, &quot;ETag mismatch&quot;);<br>        }<br>        throw e;<br>    }<br>}</pre><p><strong>GlobalExceptionHandler</strong> maps that exception to HTTP 412:</p><pre>@ExceptionHandler(ETagConflictException.class)<br>public ResponseEntity&lt;ErrorResponse&gt; handleETagConflict(...) {<br>    return build(HttpStatus.PRECONDITION_FAILED, ...);  // 412<br>}<br><br>@ExceptionHandler({DataIntegrityViolationException.class,<br>                   UncategorizedSQLException.class})<br>public ResponseEntity&lt;ErrorResponse&gt; handleOracleETagError(...) {<br>    // Walk cause chain for ORA-42699 / ORA-40896<br>    // Returns 412 if found, 409 otherwise<br>}</pre><p>Five files touched, one new file (ETagConflictException.java). The Duality View OCC implementation is complete.</p><h3>The JPA @Version Implementation</h3><p>To make the comparison meaningful, we implemented the standard JPA answer to the same problem: @Version on WfProcessInstanceEntity. A developer familiar with Spring Boot would reach for this first.</p><p><strong>Schema migration.</strong> @Version requires a dedicated column:</p><pre># V008__occ_version.yaml<br>- addColumn:<br>    tableName: wf_process_instance<br>    columns:<br>      - column:<br>          name: occ_version<br>          type: BIGINT<br>          defaultValueNumeric: 0<br>          constraints:<br>            nullable: false</pre><p>Entity annotation:</p><pre>@Version<br>@Column(name = &quot;occ_version&quot;, nullable = false)<br>@Builder.Default<br>private Long occVersion = 0L;</pre><p>The @Builder.Default is necessary. Without it, Lombok&#39;s generated builder passes null for occVersion, which violates the NOT NULL constraint on every INSERT. This is not obvious from reading the @Version documentation.</p><p><strong>Forcing the version check on setVariables.</strong> @Version is only verified when Hibernate emits an UPDATE for the annotated entity. If the entity is not dirty, Hibernate skips the UPDATE entirely and the version column is never checked. setVariables writes to wf_instance_variable, not to wf_process_instance, so without intervention the root entity stays clean. Without the fix, @Version provides no protection — the benchmark produced results identical to the no-OCC baseline.</p><p>The fix is to explicitly mark the root entity as dirty before the commit:</p><pre>public List&lt;VariableResponse&gt; setVariables(Long instanceId,<br>                                            List&lt;VariableRequest&gt; variables) {<br>    WfProcessInstanceEntity instance = instanceRepo.findById(instanceId)...;<br>    persistVariables(instance, variables);<br><br>    // Force dirty mark so Hibernate emits an UPDATE and checks occ_version.<br>    // Without this line, @Version is never verified for variable updates.<br>    instance.setUpdatedAt(LocalDateTime.now());<br>    instanceRepo.save(instance);<br><br>    return getVariableList(instanceId);<br>}</pre><p>Every operation that should be protected by @Version requires this explicit touch.</p><p><strong>Concurrent INSERT race on wf_instance_variable.</strong> The original persistVariables method followed a check-then-act pattern: SELECT the variable, INSERT if absent, UPDATE if present. Under concurrent load two sessions both find the variable absent and both attempt INSERT, producing ORA-00001 on the unique key UK_VAR_INST_KEY.</p><p>The first attempt was a standard upsert via Oracle MERGE:</p><pre>MERGE INTO wf_instance_variable tgt<br>USING (SELECT :instanceId AS instance_id, :key AS var_key FROM dual) src<br>   ON (tgt.instance_id = src.instance_id AND tgt.var_key = src.var_key)<br>WHEN MATCHED THEN<br>   UPDATE SET tgt.var_type = :type, tgt.var_value = :value<br>WHEN NOT MATCHED THEN<br>   INSERT (instance_id, var_key, var_type, var_value)<br>   VALUES (:instanceId, :key, :type, :value);</pre><p>This does not solve the concurrent INSERT race. MERGE is not atomic across sessions: two sessions can both evaluate WHEN NOT MATCHED against the same absent row before either commits, then both attempt the INSERT. The second INSERT violates UK_VAR_INST_KEY with ORA-00001, regardless of whether the upsert was expressed as MERGE or as a manual SELECT → INSERT/UPDATE. The constraint violation is unavoidable without either serializing access to the row (a lock) or catching the duplicate and retrying — which is exactly what VariableUpsertHelper does.</p><p>The working solution uses JdbcTemplate with a ConnectionCallback to catch SQLIntegrityConstraintViolationException before Spring&#39;s exception translators see it. Once the translators touch the exception they mark the transaction as rollback-only, and any subsequent work in that transaction fails with UnexpectedRollbackException regardless of what the application code does.</p><pre>@Component<br>public class VariableUpsertHelper {<br><br>    public void upsert(Long instanceId, String key, String type, String value) {<br>        int updated = jdbcTemplate.update(SQL_UPDATE, type, value, instanceId, key);<br>        if (updated &gt; 0) return;<br><br>        boolean inserted = jdbcTemplate.execute((Connection conn) -&gt; {<br>            try (var stmt = conn.prepareStatement(SQL_INSERT)) {<br>                stmt.setLong(1, instanceId); stmt.setString(2, key);<br>                stmt.setString(3, type);     stmt.setString(4, value);<br>                stmt.executeUpdate();<br>                return true;<br>            } catch (SQLIntegrityConstraintViolationException e) {<br>                return false;  // concurrent INSERT — caller retries with UPDATE<br>            }<br>        });<br><br>        if (!inserted) {<br>            jdbcTemplate.update(SQL_UPDATE, type, value, instanceId, key);<br>        }<br>    }<br>}</pre><p>@Transactional(REQUIRES_NEW) on a helper bean was the first attempt. It requires a second connection from the pool for each subtransaction. With ten concurrent writers holding ten connections, the pool is exhausted and the subtransactions cannot start. REQUIRES_NEW causes connection pool starvation at exactly the concurrency levels a benchmark tests.</p><p>The exception handler for the JPA path maps to HTTP 409:</p><pre>@ExceptionHandler({OptimisticLockException.class,<br>                   ObjectOptimisticLockingFailureException.class})<br>public ResponseEntity&lt;ErrorResponse&gt; handleOptimisticLock(...) {<br>    return build(HttpStatus.CONFLICT, ...);  // 409<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QB-LIn9tBrufTOYyYcn19w.png" /><figcaption>Table 1 — Implementation cost comparison: Duality View ETag OCC vs. JPA @Version</figcaption></figure><p>Line counts include production code only — no tests, no blank lines, no comments. Schema migration lines count the Liquibase YAML changeset. The VariableUpsertHelper accounts for 75 of the 135 JPA lines; it exists solely to work around the concurrent INSERT race that @Version does not address.</p><p>The three framework issues in the JPA path each required understanding a separate layer of the stack.</p><p>Oracle MERGE is not atomic for concurrent inserts when the row does not yet exist: two sessions both evaluate WHEN NOT MATCHED before either commits, and both proceed to INSERT. That is the first issue.</p><p>Catching the resulting DataIntegrityViolationException inside a @Transactional method does not recover the transaction. Spring&#39;s exception translators run at the proxy boundary, before the application&#39;s catch block executes, and mark the transaction rollback-only. Any subsequent work in that transaction fails with UnexpectedRollbackException regardless of what the application code does.</p><p>The REQUIRES_NEW workaround compounds this: suspending the caller&#39;s transaction and opening a new one requires a second connection from the pool. With pool size equal to the number of concurrent writers, no connections are available for the subtransactions — starvation at exactly the load a benchmark tests.</p><p>None of these are corner cases. They follow directly from combining Spring’s transaction proxy model, Hibernate’s dirty-checking behavior, and Oracle’s constraint enforcement under concurrent load.</p><h3>Benchmark Results</h3><p>We ran the benchmark against PUT /workflow/{id}/variables, with N workers performing parallel GET followed by parallel PUT on the same instance. The benchmark is a Python script using httpx and asyncio, with a barrier synchronization pattern to maximize the collision window between the GET and PUT phases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnW3_IgkOqxNGcIz9-L-_w.png" /><figcaption>Table 2 — Benchmark results: PUT /workflow/{id}/variables — parallel GET → parallel PUT, N concurrent workers</figcaption></figure><p>In terms of concurrency protection, both approaches are equivalent. With OCC active, whether via @Version or ETag, exactly one writer succeeds and the rest receive an appropriate error response. The successes=2 results at 10 workers in the JPA + @Version and DV (implicit OCC) rows reflect a specific timing condition: with barrier synchronization, all ten workers complete their GET before any PUT is issued. Under local single-machine scheduling, two PUT requests can occasionally reach the database in a window where the first commit completes and updates the document state before the second PUT&#39;s ETag is validated — both pass. This does not occur in the DV + If-Match rows, where the client ETag is validated against the value received at GET time, making the window narrower. All results are from single runs on a development laptop; the numbers establish the presence or absence of OCC protection, not throughput characteristics.</p><p>What the benchmark does establish is the no-OCC baseline: all workers return 200, only one writer’s data persists, and the client receives no indication that anything went wrong.</p><h3>What the Numbers Do Not Capture</h3><p>Two properties that don’t appear in any table matter more than the line count difference.</p><p><strong>Coverage across tables.</strong> The Duality View ETag is computed over wf_process_instance, wf_instance_activity, and wf_instance_variable together. Any change to any row in any of those tables changes the ETag. A developer cannot accidentally leave a table unprotected because the protection is not attached to any individual table.</p><p>With @Version, the protection covers only the entity carrying the annotation. setVariables modifies wf_instance_variable. Without the explicit instance.setUpdatedAt(); instanceRepo.save(instance) call, the version column is never checked, and the benchmark demonstrated this directly: ten workers, @Version present in the code, zero conflicts, silent data loss. The discipline of touching the root entity must be applied consistently to every operation the team wants to protect.</p><p><strong>Client visibility.</strong> ETag and If-Match are HTTP standards defined in RFC 9110. A client sending If-Match knows it is making a conditional request. When the server responds with 412, the client has enough context to tell the user that the record changed since it was last loaded. The @Version mechanism is invisible at the HTTP level: the server translates the OptimisticLockException to a 409, and the client receives a generic conflict response with no information about what changed or when.</p><p>One additional observation from the benchmark deserves mention. The Duality View OCC activates even without the If-Match header. The buildMetadataForWrite method always includes the _metadata fetched during findById. Oracle validates the round-trip hash on every UPDATE regardless of whether the client sent If-Match. This is why the &quot;DV — auto OCC&quot; rows in the benchmark show conflict detection even without explicit headers.</p><h3>When to Use Each Approach</h3><p>The implementation cost and failure modes differ in ways that matter depending on context.</p><p>Duality View ETags fit well when the data model maps cleanly to a document view, when clients are written in different languages and benefit from HTTP-standard semantics, and when the team wants conflict detection that works regardless of whether individual operations remember to touch a particular entity.</p><p>One cost worth acknowledging: the ETag is recomputed over every participating table on each UPDATE. For WfProcessInstanceDoc,three tables, a bounded set of variables — this is negligible. For a Duality View spanning many joined tables or large child arrays, the hash computation becomes proportionally more expensive. Oracle provides the NOCHECK annotation precisely for this trade-off: annotating a table or column with NOCHECK excludes it from ETag calculation, reducing computation cost at the price of narrowing the concurrency protection scope. The Oracle documentation notes that the performance improvement is more significant for larger documents. In the BPMNFlow runtime layer, all three tables contribute to the conflict surface that matters, so NOCHECK would not be appropriate, but teams with wider views should evaluate which fields genuinely need to participate in the hash.</p><p>JPA @Version remains appropriate when the application runs with dualityEnabled=false, when entity lifecycles are complex enough that Duality View mapping is not practical, or when the team is more familiar with Hibernate semantics than with JDBC-level document management. The BPMNFlow metamodel layer (bpmn_process, bpmn_element, process_activity) is query-heavy and does not benefit from the document view model, so it stays as JPA. Both layers coexist in the same application, gated by bpmnflow.duality.enabled.</p><h3>Conclusion</h3><p>The @JsonIgnoreProperties(ignoreUnknown = true) annotation that most Duality View tutorials apply to suppress _metadata discards precisely the field that distinguishes Duality Views from a JSON serialization layer on top of JPA.</p><p>Implementing the ETag path took approximately 53 lines of production code across five modified files and one new file (ETagConflictException.java), and did not surface any issues with the framework stack. Implementing the @Version equivalent took approximately 135 lines across five modified files and two new files, and required working through three separate issues in the Spring/Hibernate/Oracle interaction. Seventy-five of those 135 lines belong to VariableUpsertHelper — code that exists solely to work around the concurrent INSERT race that @Version does not address. Without that workaround the protection silently disappears, as the benchmark demonstrated directly.</p><p>The difference is in what it takes to get to correct, and in the fact that the Duality View path fails loudly when something goes wrong, while the JPA path has at least one configuration error (@Version active but root entity not touched) that fails silently and produces the same observable result as having no OCC at all.</p><p><em>The complete implementation is available in the </em><a href="https://github.com/jefersonferr/bpmnflow-process-runtime-oracle"><em>bpmnflow-process-runtime-oracle</em></a><em> repository. The benchmark scripts are in the </em><em>benchmark/ directory.</em></p><p><em>References:</em></p><p><a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/jsnvu/using-optimistic-concurrency-control-duality-views.html"><em>Oracle Docs — OCC with Duality Views</em></a><em> · </em><a href="https://martincarstenbach.com/2026/02/03/optimistic-locking-made-easy-the-power-of-etags-in-action/"><em>Martin Carsten Bach — ETags in Action</em></a><em> · </em><a href="https://www.rfc-editor.org/rfc/rfc9110#section-8.8.3"><em>RFC 9110 §8.8.3</em></a><em> · </em><a href="https://github.com/oracle/spring-cloud-oracle/issues/164"><em>GitHub Issue #164</em></a><em> </em>· <a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/jsnvu/using-system-change-number-scn-json-document.html">Oracle Docs — SCN and the </a><a href="https://docs.oracle.com/en/database/oracle/oracle-database/26/jsnvu/using-system-change-number-scn-json-document.html">asof field</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecbcfc90b8cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Look at Oracle JSON Duality Views in a Real Spring Boot App]]></title>
            <link>https://medium.com/@jefersonferr/a-practical-look-at-oracle-json-duality-views-in-a-real-spring-boot-app-27c11921d328?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c11921d328</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[oracle-json-duality-views]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Sat, 09 May 2026 03:15:55 GMT</pubDate>
            <atom:updated>2026-05-09T03:15:55.730Z</atom:updated>
            <content:encoded><![CDATA[<h4>A real workflow runtime with 17 tables, N+1 traps, and enums with business logic. Here is what Duality Views solved, what they did not, and what the numbers look like when the view handles reads and writes natively.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cljq7Lz-ECyvc-uEgmZpEw.png" /></figure><p>BPMNFlow is a BPMN runtime with 17 tables and 12 JPA entities. Its persistence layer requires four queries with JOIN FETCH, one DISTINCT to neutralize cartesian products, and explicit handling for MultipleBagFetchException. That is the price of JPA when the model is hierarchical. JSON Relational Duality Views, introduced in Oracle 23ai, promise to eliminate that cost: data stays in normalized relational tables, but is exposed to applications as hierarchical JSON documents. Reads and writes go through the view; Oracle handles the translation. This article evaluates Duality Views against actual code, including benchmark results for reads and writes against 50,000 workflow instances, 315,835 activities, and 213,451 variables.</p><h3>Anatomy of BPMNFlow</h3><p>BPMNFlow’s runtime parses .bpmn XML files, persists the structural model, and then manages the lifecycle of process instances: creating them, advancing them through activities, tracking variables, evaluating rules.</p><p>The domain has five layers, each with a different concern, from the static BPMN structure down to live workflow execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*bW6UxOL9mRzWLkP2s4oPIA.png" /><figcaption>Table 1 — The five layers of BPMNFlow’s domain model, from static process structure to live runtime state.</figcaption></figure><p>Everything connects to BpmnProcessVersionEntity. Eight @OneToMany collections, seven entities holding a FK back to it.</p><pre>@Entity<br>@Table(name = &quot;bpmn_process_version&quot;)<br>public class BpmnProcessVersionEntity {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.SEQUENCE, <br>                    generator = &quot;bpmn_version_seq&quot;)<br>    private Long id;<br><br>    @ManyToOne(fetch = FetchType.LAZY)<br>    @JoinColumn(name = &quot;process_id&quot;, nullable = false)<br>    private BpmnProcessEntity process;<br><br>    @Column(name = &quot;bpmn_xml&quot;, columnDefinition = &quot;CLOB&quot;)<br>    @Lob<br>    private String bpmnXml;<br><br>    @Column(name = &quot;config_yaml&quot;, columnDefinition = &quot;CLOB&quot;)<br>    @Lob<br>    private String configYaml;<br><br>    @OneToMany(mappedBy = &quot;processVersion&quot;, cascade = CascadeType.ALL, <br>               orphanRemoval = true)<br>    private List&lt;BpmnParticipantEntity&gt; participants = new ArrayList&lt;&gt;();<br><br>    @OneToMany(mappedBy = &quot;processVersion&quot;, cascade = CascadeType.ALL, <br>               orphanRemoval = true)<br>    private List&lt;BpmnLaneEntity&gt; lanes = new ArrayList&lt;&gt;();<br><br>    @OneToMany(mappedBy = &quot;processVersion&quot;, cascade = CascadeType.ALL, <br>               orphanRemoval = true)<br>    private List&lt;BpmnElementEntity&gt; elements = new ArrayList&lt;&gt;();<br><br>    @OneToMany(mappedBy = &quot;processVersion&quot;, cascade = CascadeType.ALL, <br>               orphanRemoval = true)<br>    private List&lt;BpmnSequenceFlowEntity&gt; sequenceFlows = new ArrayList&lt;&gt;();<br><br>    @OneToMany(mappedBy = &quot;processVersion&quot;, cascade = CascadeType.ALL, <br>               orphanRemoval = true)<br>    private List&lt;BpmnRuleEntity&gt; rules = new ArrayList&lt;&gt;();<br><br>    @OneToMany(mappedBy = &quot;processVersion&quot;, cascade = CascadeType.ALL, <br>               orphanRemoval = true)<br>    private List&lt;BpmnActivityStepEntity&gt; activitySteps = new ArrayList&lt;&gt;();<br><br>    // ... status, versionTag, deployedAt, etc.<br>}</pre><p>Every @OneToMany here is FetchType.LAZY by default. That&#39;s correct JPA practice. Any code path that traverses these collections outside a Hibernate session triggers a LazyInitializationException. If you’re inside a transaction but haven’t fetched eagerly, it quietly fires N queries.</p><h3>The JPA Implementation</h3><h4>The N+1 Problem</h4><p>WfProcessInstanceRepository exists to load a complete process instance graph: the instance itself, its activity instances, each activity&#39;s variables, and the activity steps backing them. Here’s what that looks like in practice:</p><pre>@Repository<br>public interface WfProcessInstanceRepository<br>        extends JpaRepository&lt;WfProcessInstanceEntity, Long&gt; {<br><br>    @Query(&quot;&quot;&quot;<br>        SELECT DISTINCT i FROM WfProcessInstanceEntity i<br>        LEFT JOIN FETCH i.activityInstances ai<br>        LEFT JOIN FETCH ai.variables<br>        LEFT JOIN FETCH ai.activityStep step<br>        LEFT JOIN FETCH step.element<br>        WHERE i.id = :id<br>    &quot;&quot;&quot;)<br>    Optional&lt;WfProcessInstanceEntity&gt; findByIdWithFullGraph(<br>        @Param(&quot;id&quot;) Long id);<br><br>    @Query(&quot;&quot;&quot;<br>        SELECT DISTINCT i FROM WfProcessInstanceEntity i<br>        LEFT JOIN FETCH i.activityInstances ai<br>        LEFT JOIN FETCH ai.variables<br>        WHERE i.processVersion.id = :versionId<br>        AND i.status = :status<br>    &quot;&quot;&quot;)<br>    List&lt;WfProcessInstanceEntity&gt; findByVersionAndStatus(<br>        @Param(&quot;versionId&quot;) Long versionId,<br>        @Param(&quot;status&quot;) InstanceStatus status<br>    );<br><br>    @Query(&quot;&quot;&quot;<br>        SELECT DISTINCT i FROM WfProcessInstanceEntity i<br>        LEFT JOIN FETCH i.activityInstances ai<br>        LEFT JOIN FETCH ai.variables<br>        LEFT JOIN FETCH ai.activityStep<br>        WHERE i.correlationKey = :correlationKey<br>        AND i.status IN :statuses<br>    &quot;&quot;&quot;)<br>    List&lt;WfProcessInstanceEntity&gt; findActiveByCorrelationKey(<br>        @Param(&quot;correlationKey&quot;) String correlationKey,<br>        @Param(&quot;statuses&quot;) List&lt;InstanceStatus&gt; statuses<br>    );<br>}</pre><p>It’s the <em>correct</em> JPA code for a model this complex. The DISTINCT is there because JOIN FETCH produces cartesian products that Hibernate deduplicates in memory. The four separate queries exist because you can&#39;t JOIN FETCH more than one collection at once without risking a cartesian explosion. Hibernate throws a MultipleBagFetchException if you try.</p><p>But every new feature that needs a slightly different graph shape requires a new named query. This is the maintenance tax.</p><p>Pagination compounds the problem. Combining Pageable with JOIN FETCH on a collection causes Hibernate to fetch all matching rows from the database and apply the page limit in memory, a warning known as HHH90003004. The correct fix is a JPQL projection query that returns only the fields needed for the list response and joins only the active activity step rather than loading the full activity history for each instance. It is not Hibernate&#39;s default behavior, and it requires a developer to recognize the problem and write the projection explicitly.</p><h4>The EAV Table and Why It Has No Foreign Key</h4><p>BpmnExtensionPropertyEntity implements a polymorphic key-value store. Participants, lanes, elements, and rules can all have arbitrary extension properties defined by process authors in the BPMN file.</p><pre>@Entity<br>@Table(name = &quot;bpmn_extension_property&quot;)<br>public class BpmnExtensionPropertyEntity {<br>@Id<br>    @GeneratedValue(strategy = GenerationType.SEQUENCE, <br>                    generator = &quot;ext_prop_seq&quot;)<br>    private Long id;<br>    @Column(name = &quot;owner_type&quot;, nullable = false)<br>    private String ownerType;   // &quot;ELEMENT&quot;, &quot;LANE&quot;, &quot;PARTICIPANT&quot;, etc.<br>    @Column(name = &quot;owner_id&quot;, nullable = false)<br>    private Long ownerId;<br>    @Column(name = &quot;prop_key&quot;, nullable = false)<br>    private String propKey;<br>    @Column(name = &quot;prop_value&quot;)<br>    private String propValue;<br>}</pre><p>There is no @ManyToOne pointing to any of the owner types. This is intentional. Hibernate does not support a polymorphic @ManyToOne where a single column references different tables based on a discriminator, not without @Any, which brings its own complexity and JDBC vendor-specific behavior. The EAV table was designed this way to avoid that constraint, with the trade-off that referential integrity is enforced at the service layer, not the database.</p><h4>Enums That Do More Than Label</h4><p>BPMNFlow’s VariableType enum is not a simple label. It contains the validation and conversion logic for workflow variables:</p><pre>public enum VariableType {<br>    STRING {<br>        @Override<br>        public Object convert(String raw) { return raw; }<br>        @Override<br>        public void validate(String raw) {<br>            if (raw == null) <br>                throw new VariableValidationException<br>                              (&quot;STRING cannot be null&quot;);<br>        }<br>    },<br>    INTEGER {<br>        @Override<br>        public Object convert(String raw) {<br>            try { return Integer.parseInt(raw); }<br>            catch (NumberFormatException e) {<br>                throw new VariableValidationException<br>                              (&quot;Cannot convert to INTEGER: &quot; + raw);<br>            }<br>        }<br>        @Override<br>        public void validate(String raw) {<br>            convert(raw); // conversion IS validation here<br>        }<br>    },<br>    BOOLEAN {<br>        @Override<br>        public Object convert(String raw) {<br>            if (&quot;true&quot;.equalsIgnoreCase(raw) || &quot;false&quot;.equalsIgnoreCase(raw))<br>                return Boolean.parseBoolean(raw);<br>            throw new VariableValidationException<br>                          (&quot;Invalid BOOLEAN value: &quot; + raw);<br>        }<br>        @Override<br>        public void validate(String raw) { convert(raw); }<br>    },<br>    DATE {<br>        @Override<br>        public Object convert(String raw) {<br>            try { return LocalDate.parse(raw); }<br>            catch (DateTimeParseException e) {<br>                throw new VariableValidationException<br>                              (&quot;Invalid DATE format: &quot; + raw);<br>            }<br>        }<br>        @Override<br>        public void validate(String raw) { convert(raw); }<br>    };<br>    public abstract Object convert(String raw);<br>    public abstract void validate(String raw);<br>}</pre><p>This logic has no natural equivalent in a database schema. The type is stored as a string (@Enumerated(EnumType.STRING)), but the behavior: validation and conversion, is entirely a Java concern. Any migration away from JPA has to account for where this logic lives.</p><h4>Concurrent Deploys and Pessimistic Locking</h4><p>When two requests try to deploy different versions of the same process simultaneously, BPMNFlow uses a database-level lock to serialize them:</p><pre>@Repository<br>public interface BpmnProcessRepository <br>extends JpaRepository&lt;BpmnProcessEntity, Long&gt; {<br>@Lock(LockModeType.PESSIMISTIC_WRITE)<br>   @Query(&quot;SELECT p FROM BpmnProcessEntity p WHERE p.processKey = :processKey&quot;)<br>   Optional&lt;BpmnProcessEntity&gt; findByProcessKeyForUpdate(<br>      @Param(&quot;processKey&quot;) String processKey);<br>}</pre><p>The calling service holds this lock for the duration of the deploy transaction. That is the subject of the next article.</p><h4>How JSON Relational Duality Views Work</h4><p>Oracle introduced JSON Relational Duality Views with Database 23ai. The feature is fully available in the current release, Oracle AI Database 26ai. Data is still stored in normalized relational tables with all the integrity constraints and indexing you’d expect, but exposed to applications as hierarchical JSON documents.</p><p>The JSON representation is generated on demand from the underlying tables. You write to the view as a JSON document; Oracle translates that write into the appropriate DML across the related tables.</p><p>In practice:</p><ul><li>No @Entity classes, you work with POJOs or records</li><li>No Hibernate session lifecycle management</li><li>No FetchType.LAZY decisions</li><li>No JOIN FETCH queries to write</li><li>The document shape you need is defined once, in SQL</li></ul><p>Duality Views require that the underlying tables have primary keys, foreign keys, and unique keys defined. Without these, Oracle cannot guarantee document consistency. BPMNFlow’s existing schema satisfies this for most tables, the exception being bpmn_extension_property, which deliberately has no FK to its owner.</p><h3>Rewriting the Runtime Layer with Duality Views</h3><h4>The Process Instance Document</h4><p>The runtime layer (wf_* tables) is the best fit for Duality Views. A running process instance, with its activity history and variables, maps to a single hierarchical document:</p><pre>CREATE OR REPLACE JSON RELATIONAL DUALITY VIEW wf_process_instance_dv AS<br>SELECT JSON {<br>    &#39;_id&#39;             : i.instance_id,<br>    &#39;externalId&#39;      : i.external_id,<br>    &#39;status&#39;          : i.status,<br>    &#39;startedAt&#39;       : i.started_at,<br>    &#39;finishedAt&#39;      : i.finished_at,<br>    &#39;processVersionId&#39;: i.process_version_id,<br>    &#39;activities&#39;      : [<br>        SELECT JSON {<br>            &#39;id&#39;         : a.id,<br>            &#39;stepKey&#39;    : a.step_key,<br>            &#39;status&#39;     : a.status,<br>            &#39;startedAt&#39;  : a.started_at,<br>            &#39;finishedAt&#39; : a.finished_at,<br>            &#39;variables&#39;  : [<br>                SELECT JSON {<br>                    &#39;id&#39;        : v.id,<br>                    &#39;varKey&#39;    : v.var_key,<br>                    &#39;varValue&#39;  : v.var_value,<br>                    &#39;varType&#39;   : v.var_type<br>                }<br>                FROM wf_instance_variable v WITH INSERT UPDATE DELETE<br>                WHERE v.instance_id = i.instance_id<br>            ]<br>        }<br>        FROM wf_instance_activity a WITH INSERT UPDATE DELETE<br>        WHERE a.instance_id = i.instance_id<br>    ]<br>}<br>FROM wf_process_instance i WITH INSERT UPDATE DELETE;</pre><p>The Java side becomes:</p><pre>public record WfVariable(<br>    Long id, <br>    String varKey, <br>    String varValue, <br>    String varType<br>) {}<br><br>public record WfActivityInstance(<br>    Long id,<br>    String stepKey,<br>    String status,<br>    OffsetDateTime startedAt,<br>    OffsetDateTime finishedAt,<br>    List&lt;WfVariable&gt; variables<br>) {}<br><br>public record WfProcessInstanceDoc(<br>    @JsonProperty(&quot;_id&quot;)  Long id,<br>    String externalId,<br>    String status,<br>    OffsetDateTime startedAt,<br>    OffsetDateTime finishedAt,<br>    Long processVersionId,<br>    List&lt;WfActivityInstance&gt; activities<br>) {}</pre><blockquote><strong>Implementation note:</strong> The records above are simplified for clarity. The production records require two additional annotations. @JsonIgnoreProperties(ignoreUnknown = true) is mandatory on every record. Oracle Database injects a _metadata field into every Duality View document for ETag-based concurrency control, and without this annotation Jackson throws UnrecognizedPropertyException on deserialization. Field mappings that differ from the JSON key name also need @JsonProperty(&quot;_id&quot;) on the id field to match Oracle&#39;s document key convention.</blockquote><p>And the repository:</p><pre>@Repository<br>public class WfProcessInstanceDualityRepository {<br><br>    private static final String FIND_BY_ID = &quot;&quot;&quot;<br>            SELECT json_serialize(data returning clob)<br>            FROM wf_process_instance_dv v<br>            WHERE v.data.&quot;_id&quot; = ?<br>            &quot;&quot;&quot;;<br><br>    private static final String UPDATE_BY_ID = &quot;&quot;&quot;<br>            UPDATE wf_process_instance_dv v SET data = ?<br>            WHERE v.data.&quot;_id&quot; = ?<br>            &quot;&quot;&quot;;<br><br>    private final JdbcTemplate jdbc;<br>    private final RowMapper&lt;WfProcessInstanceDoc&gt; rowMapper;<br><br>    public Optional&lt;WfProcessInstanceDoc&gt; findById(Long id) {<br>        List&lt;WfProcessInstanceDoc&gt; result = jdbc.query(FIND_BY_ID, rowMapper, id);<br>        return result.isEmpty() ? Optional.empty() : Optional.of(result.getFirst());<br>    }<br><br>    public WfProcessInstanceDoc update(WfProcessInstanceDoc doc) {<br>        jdbc.update(con -&gt; {<br>            PreparedStatement ps = con.prepareStatement(UPDATE_BY_ID);<br>            ps.setString(1, mapper.writeValueAsString(doc));<br>            ps.setLong(2, doc.id());<br>            return ps;<br>        });<br>        return findById(doc.id()).orElseThrow();<br>    }<br>}</pre><p>Compare this to WfProcessInstanceRepository: four custom JPQL queries with JOIN FETCH, a DISTINCT keyword to handle cartesian products, and explicit graph management. The Duality approach replaces all of that with one view definition and direct SQL.</p><p>When you insert or update a document, Oracle translates the operation into INSERT or UPDATE statements across wf_process_instance, wf_instance_activity, and wf_instance_variable atomically. The cascade management that you&#39;d otherwise express with CascadeType.ALL and orphanRemoval = true is handled by the view definition.</p><h3>Where Duality Views Don’t Help</h3><p>Some specific characteristics of BPMNFlow’s model sit outside what Duality Views can address: behavioral logic in enums, polymorphic associations without foreign keys, and field-level lazy loading on large CLOBs. Duality Views don’t always reduce the amount of application code; in some cases, they shift complexity from Java to SQL and infrastructure without any net gain.</p><h4>The VariableType Enum</h4><p>VariableType.validate() and VariableType.convert() are Java logic. The type is stored as a string in wf_variable.var_type, and Duality Views will round-trip that string. But when your application reads a WfVariable record and calls varType.convert(varValue), you need a Java enum with that logic.</p><p>You can’t push VariableType.convert() into a database function and keep it portable, language-idiomatic, and testable. This logic stays in Java regardless of your persistence strategy.</p><h4>The EAV Polymorphism</h4><p>BpmnExtensionPropertyEntity uses ownerType and ownerId to associate extension properties with any structural entity, without a foreign key. This is by design: JPA&#39;s @Any annotation (the standard Hibernate extension for polymorphic associations) adds complexity and isn&#39;t consistently supported across JDBC drivers.</p><p>Duality Views require FK relationships to nest documents. There’s no FK from bpmn_extension_property to any owner table, so you can&#39;t nest extension properties inside a participant or element document. You&#39;d either need to add FK columns, changing the schema design, or fetch extension properties separately and join them in application code, which is exactly what the current JPA design does.</p><h4>Large CLOBs in Documents</h4><p>bpmnXml and configYaml are Oracle CLOB fields. In the JPA model, they&#39;re annotated with @Lob and fetched lazily. In a Duality View document, they&#39;re part of the JSON payload.</p><p>For a typical BPMN file, bpmnXml can be several hundred kilobytes. Including it in every document fetch that includes the process version is a potential performance regression. You&#39;d either exclude it from the view, accepting that you need a separate query for it, or accept the payload size. Neither option gives you the field-level control that FetchType.LAZY provides.</p><h4>Where Duality Views Fit</h4><p>Duality Views work well for the runtime layer. For the structural and extension layers, JPA remains the better fit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*V3KZA8Kvtn9h6RbtGEjdJw.png" /><figcaption>Table 2 — Where Duality Views fit in BPMNFlow’s domain model.</figcaption></figure><h3>Before vs. After</h3><h4>Lines of Code</h4><p>Measuring the full cost of each approach, Java service, repository, and infrastructure layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*3401G4w1DF0OgN0aC2o-3Q.png" /><figcaption>Table 3 — Lines of Code: JPA vs Duality Views (runtime layer only)</figcaption></figure><p>The reasons are the problems that surfaced during implementation that JPA absorbs without the developer noticing:</p><p><em>Transaction boundary:</em> the JdbcTemplate that reads from the Duality View uses a separate JDBC connection from the JPA EntityManager. Reading a document immediately after a JPA write requires the write transaction to have committed first. The native Duality View write path avoids this entirely, since both the INSERT and the read-back use the same JdbcTemplate connection. For structural lookups (process version, rules, activity definitions), JPA is still used because those tables are not part of the runtime view.</p><p><em>Lazy proxy initialization:</em> @ManyToOne and @OneToMany associations returned from JPA are proxies. Outside an open session, any field access throws LazyInitializationException. The solution is a dedicated query with LEFT JOIN FETCH a.element LEFT JOIN FETCH a.conclusions, explicit code that Hibernate would otherwise handle through its session lifecycle.</p><p>The Duality approach trades Java boilerplate for a SQL view definition, but also introduces infrastructure work that has no parallel in JPA. Whether that’s a good trade depends not just on team preference, but on how much of the complexity you want to own in Java versus at the database boundary.</p><h4>N+1 Elimination</h4><p>The JPA approach requires JOIN FETCH to avoid N+1. If a developer forgets, the problem is silent at first: the test passes, the feature ships, and then a performance review reveals 30 queries per request.</p><p>Duality Views eliminate that bug entirely. The document is always fully assembled by the database. There’s no concept of “did you remember to fetch this association?” The association is structural to the view.</p><h3><strong>Performance: Measured</strong></h3><p>To quantify the runtime difference, we ran three benchmark scenarios against 50,000 workflow instances, 315,835 activities, and 213,451 variables in Oracle Autonomous AI Database 26ai Free Tier — note that free tier CPU/IO limits may affect absolute numbers; the relative comparison still holds. Both configurations use Oracle Universal Connection Pool (UCP) with initial-pool-size: 5. The JPA implementation uses a JPQL projection query for listing that returns exactly the fields needed for the summary response. The Duality View implementation sends both reads and writes through the view natively, using JdbcTemplate with json_serialize for reads and INSERT/UPDATE with the Jackson-serialized document for writes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*8A_uuK-uPycUaN_U1JbIsQ.png" /><figcaption>Table 4 — Performance summary across the three benchmark scenarios.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*eTU5gaGwBmgS33035RlDJg.png" /><figcaption>Table 5 — Reading a single instance by primary key: 1,000 requests, 10 concurrent workers</figcaption></figure><p>JPA leads on single-record reads. The Duality View adds overhead from assembling the JSON document from the underlying tables inside Oracle. The difference is small enough that factors outside the persistence layer would dominate in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*LR4CARoMBNrYygEQMsgF_g.png" /><figcaption>Table 6 — Writing new instances: 200 instances, 10 concurrent workers (workflow start + activity complete)</figcaption></figure><p>The Duality View write path outperforms JPA by roughly 20% at the median and delivers 20% higher throughput. The reason is structural: starting a new workflow instance in JPA requires three separate INSERT statements: one for wf_process_instance, one for wf_instance_activity, and one or more for wf_instance_variable. The Duality View receives a single JSON document and Oracle decomposes it into the same DML atomically inside the database. One network round-trip instead of three.</p><p><em>Optimistic concurrency control:</em> Oracle Duality Views use an ETag mechanism for concurrency control instead of row-level locks. Every document returned by the view includes a _metadata.etag field, a hash of the current row state across all tables that make up the document. When updating a document, the application must include the ETag from the most recent read in the update payload. If another session has modified the document between the read and the write, Oracle rejects the update with ORA-40896. The application then re-reads the document to get the current ETag and retries.</p><p>This is the trade-off for lock-free concurrency: no blocking, but occasional retries under contention. In the benchmarks above, each worker touched a distinct instance, so ETag collisions were rare. A workflow where multiple sessions can advance the same instance concurrently would need explicit retry logic for this error. The Oracle documentation also describes a WITH NOCHECK directive for subcollections: when applied to the activities array, changes to activity rows would not contribute to the ETag hash of the parent instance document, reducing collisions at the cost of weaker consistency for that subset of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*ib5POwyXUcv6S96sDkCMiQ.png" /><figcaption>Table 7 — Paginated listing: 500 requests, 10 concurrent workers, page size 50</figcaption></figure><p>JPA with a projection query is three times faster at the median for paginated listing.</p><p>The Duality View listing endpoint makes two database round-trips per request. The first fetches documents from a purpose-built listing view that includes processKey, processName, and versionNumber directly in the document via JOIN with the process tables. The second is a batch query to resolve the active activity abbreviation for all 50 instances in the page.</p><p>The two-round-trip structure exists because Oracle does not allow explicit JOINs inside Duality View subcollections (ORA-40935). Including the activity abbreviation directly in the listing document would require nesting process_activity data inside the wf_instance_activity subcollection, which the engine rejects. The JPA projection query has no such constraint: it expresses the exact result in a single SQL statement with a LEFT JOIN filtered to status = ACTIVE, returning at most one row per instance.</p><h3>Choosing Between the Two</h3><p>JPA makes more sense when entities carry behavioral logic, when your model has polymorphic associations without FK support, or when you need field-level lazy loading on large CLOBs.</p><p>Duality Views make more sense when the data is naturally hierarchical, the API returns nested JSON documents, and the persistence layer has no behavioral logic. The runtime layer of BPMNFlow fits all three.</p><p>The two approaches can coexist in the same application, connected to the same tables. BPMNFlow’s structural layer stays JPA, where Hibernate’s graph management earns its complexity. The runtime layer (wf_*) moves to Duality Views.</p><h3>Conclusion</h3><p>BPMNFlow started this exercise as a well-designed JPA application, careful about N+1, intentional about its EAV design, using pessimistic locking where it needs it. The goal wasn’t to find problems with the existing code. It was to find out what Oracle Duality Views actually improve for a real model.</p><p>For the runtime layer, Duality Views deliver: the four JOIN FETCH queries in WfProcessInstanceRepository collapse into a single view definition, three entity classes become three Java records, and the cartesian product problem disappears. It&#39;s a fair trade-off. The infrastructure work that remains covers the transaction boundary between JdbcTemplate and any residual JPA lookups, and lazy proxy initialization for structural entities. For teams already on Oracle working primarily with document-shaped runtime data, that trade is favorable.</p><p>For single-record reads, JPA and the Duality View are close, with JPA holding a modest advantage at the tail latency (p95/p99). For writes, the Duality View is faster: one document into the view versus three separate inserts through Hibernate, and 60 ops/s versus 50 ops/s under load. For paginated listing, JPA with a proper projection query is faster because the relational model allows expressing the exact result in a single SQL statement, while the Duality View requires two round-trips due to a structural constraint of the product. Which scenario dominates in a given application determines which approach is the better fit for the runtime layer.</p><p>About the structural layer, particularly BpmnExtensionPropertyEntity&#39;s EAV design and VariableType&#39;s validation logic, JPA remains the right tool. The EAV table has no FK to its owner, which Duality Views require to nest documents. The behavioral logic in VariableType lives in Java and needs to stay there. Duality Views work well for hierarchical, document-shaped runtime data where the persistence layer has no behavioral logic of its own.</p><h4>Lessons Learned</h4><p>The implementation is not without friction. Duality Views require Oracle 23ai or later. ORDER BY is not supported inside subcollections (ORA-40895), so ordering of nested arrays is applied in application code. Explicit JOINs inside subcollections are also not supported (ORA-40935), which limits how much related data can be embedded in a single document fetch. The ETag mechanism requires the application to handle ORA-40896 with retry logic when concurrent modifications are detected. The Oracle documentation also describes field-level directives, including WITH NOCHECK to exclude subcollections from ETag computation and generated fields via path expressions to compute derived values inside the view definition rather than in application code. None of these were needed for BPMNFlow, but they represent levers available when the basic view definition is not enough.</p><h4>Codebase and Next Steps</h4><p>The BPMNFlow codebase is at <a href="https://github.com/jefersonferr/bpmnflow-spring-boot-demo">github.com/jefersonferr/bpmnflow-spring-boot-demo</a>. Oracle Autonomous Database Free Tier supports JSON Relational Duality Views and is a good option to run the examples above.</p><p>Coming next, BPMNFlow uses PESSIMISTIC_WRITE to prevent race conditions during concurrent process deploys. The next article shows how Duality Views handle the same problem using ETags and optimistic concurrency control to replace the database-level lock.</p><p><em>All code samples are drawn from the BPMNFlow open-source project and reflect the actual implementation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c11921d328" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provisioning an OKE Cluster with Terraform and Oracle Resource Manager]]></title>
            <link>https://medium.com/@jefersonferr/provisioning-an-oke-cluster-with-terraform-and-oracle-resource-manager-2ba4ce75dc52?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ba4ce75dc52</guid>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 01:00:10 GMT</pubDate>
            <atom:updated>2026-04-04T01:00:10.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>One stack. Two variables. Four reference architectures. How Infrastructure as Code eliminates the trade-off between Quick Create and Custom Create.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0BxOJA7h6DDoQAhds9_4Q.png" /><figcaption>Image generated with ChatGPT</figcaption></figure><h3><strong>Introduction</strong></h3><p>You have provisioned Kubernetes clusters before. You know what a Kubernetes CNI is, you understand the pratical difference between a public and a private endpoint, and you have probably had to undo a networking decision made in a hurry. In OCI, that cost is higher: two of the most consequential choices in an OKE cluster — the network plugin and the API endpoint exposure — cannot be changed after the cluster is created. There is no migration path. There is no toggle in the console. If you get it wrong, the only way forward is to destroy and rebuild.</p><p>That constraint turns what looks like an operational decision into an architectural one. And architectural decisions deserve to be made with information, not with whatever the console suggests by default.</p><p>Oracle Container Engine for Kubernetes (OKE) offers two shortcuts for getting started: Quick Create and Custom Create. The first provisions everything automatically, with networking choices that prioritize speed over control. It makes networking and security decisions for you just to get the cluster up and running in 15 minutes. The second gives you full flexibility, but requires you to manually create and configure over a dozen interdependent resources — VCN, subnets, gateways, route tables, security lists — in the correct sequence, before you can touch the cluster itself. Neither option is the right answer for a team that needs both speed and control.</p><p>This article highlights the “usability gap” between a simplified wizard and a complex manual process. If you already use <strong>Terraform</strong>, you know the workflow: write configuration, run plan, run apply, manage state. <strong>Oracle Resource Manager (ORM)</strong> brings that same workflow into OCI as a managed service. The result is a single parameterized stack that covers all four networking architectures defined in the official Oracle documentation, grounded in <strong>Infrastructure as Code (IaC)</strong> principles and ready for production from day one.</p><blockquote>The full implementation is available as an open-source repository: <a href="https://github.com/jefersonferr/oke-cluster-tf">github.com/jefersonferr/oke-cluster-tf</a></blockquote><h3><strong>Quick Create vs. Custom Create — The Trade-off</strong></h3><p>When provisioning an OKE cluster via the OCI Console, you can choose between Quick Create and Custom Create, depending on the required level of architectural control.</p><p>Quick Create prioritizes speed by automating the network stack. While this accelerates deployment, it limits flexibility and governance, often resulting in a simplified topology that may not align with enterprise standards. For example, Quick Create does not allow you to choose subnet CIDR blocks, does not separate pods into a dedicated subnet, and assigns default security list rules that may be too permissive for production environments.</p><p>In contrast, Custom Create offers full architectural control. It allows for the integration of existing network resources, support for advanced networking strategies (such as established landing zones), and strict adherence to security best practices. However, this control comes at a cost: the operator must manually create and configure over a dozen interdependent resources — VCN, subnets, gateways, route tables, security lists — in the correct sequence before the cluster can be provisioned.</p><p>The table below summarizes the key differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eWX1gviCw9Xlbna1WELVQ.png" /><figcaption>Figure 1 — Quick Create vs. Custom Create vs. IaC Stack</figcaption></figure><p>The creation of all prerequisites with the required level of control, and in the correct sequence, is one of the greatest advantages of IaC. By adopting this approach, the stack presented in this article delivers a provisioning experience that is both streamlined and consistent — similar to the simplicity of the Quick Create workflow — while preserving the flexibility, control, and level of customization typically associated with the Custom Create approach.</p><p>This significantly reduces the complexity of provisioning network infrastructure and enables a seamless, end-to-end deployment of an OKE cluster, aligned with enterprise architecture standards and best practices.</p><h3>Oracle Resource Manager — What Terraform Users Need to Know</h3><p>Oracle Resource Manager (ORM) is a managed Terraform execution service, native to OCI. It runs your configuration remotely, stores state automatically, and exposes the full plan/apply/destroy lifecycle through a console UI and API — without requiring a local toolchain.</p><p>The fundamental unit of organization in ORM is a <em>stack</em> — a cohesive entity that combines your Terraform configuration, its input variables, its state, and its full job history. This eliminates the overhead of local state management. When you run an Apply Job, ORM handles initialization, planning, and execution in a managed runner. Every plan and apply is logged and preserved in the job history tab.</p><p>Authentication requires no extra setup at the credential level. In a standard OCI Terraform workflow, you configure ~/.oci/config with API keys, a fingerprint, and a tenancy OCID. ORM eliminates this for console-driven workflows: it uses the identity of the authenticated OCI user to execute jobs. However, that identity still needs the appropriate IAM policies in place — both to operate ORM itself (create stacks, run jobs) and to provision the target resources (VCN, subnets, OKE cluster, node pool). Confirm with your administrator that the necessary grants are in place before running the first Apply Job.</p><p>Two concepts have no direct equivalent in the Terraform CLI and are worth understanding before diving into the stack.</p><p>The first is schema.yaml. This file sits alongside your Terraform files in the repository but is entirely invisible to Terraform itself — it is only read by ORM when rendering the stack creation form. It defines how variables are grouped, labeled, and constrained in the console UI, and supports conditional field visibility.</p><p>The second is drift detection. With the Terraform CLI, catching drift requires you to remember to run terraform plan periodically against the live environment. ORM makes this explicit: the stack detail page includes a dedicated <strong>Check Drift</strong> option under Terraform Actions that compares the actual state of deployed resources against the Terraform state file on demand.</p><p>The job history tab keeps a record of every plan and apply, with logs and outputs preserved per run. Figure 3, later in this article, maps each stage of this lifecycle to the equivalent Terraform CLI command for quick reference.</p><h3>Reference Network Configuration Scenarios</h3><p>Oracle documentation presents recommended network configurations for OKE across multiple scenarios, including public and private API endpoints, private worker nodes, public load balancers, and different CNI options (Flannel and OCI CNI). It details how components communicate and how to properly define subnets, gateways, and security lists, serving as a hands-on architectural guide for designing cluster networking with greater flexibility and security compared to the Quick Create approach.</p><blockquote><strong>OCI Documentation:</strong> <a href="https://docs.oracle.com/en-us/iaas/Content/ContEng/Concepts/contengnetworkconfigexample.htm">https://docs.oracle.com/en-us/iaas/Content/ContEng/Concepts/contengnetworkconfigexample.htm</a></blockquote><p>These reference scenarios are especially relevant for designing custom OKE cluster deployments. The documentation defines four distinct networking patterns, differentiated across two architectural factors:</p><ul><li><strong>Kubernetes network plugin: <br>- </strong>Flannel CNI — Examples 1 and 2<br>- OCI VCN-Native CNI — Examples 3 and 4</li><li><strong>Kubernetes API endpoint exposure:<br>- </strong>Public API — Examples 1 and 3<br>- Private API — Examples 2 and 4</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKBjV3ZK2Wmw-zaS4IXkYA.png" /><figcaption>Figure 2 — Simplified Architectural Comparison</figcaption></figure><p>In the IaC stack, these four scenarios are not four separate configurations — they are a single parameterized stack controlled by two variables:</p><pre>cni_type               = &quot;OCI_VCN_IP_NATIVE&quot;  # or &quot;FLANNEL&quot;<br>is_api_endpoint_public = true                 # or false</pre><p>All networking resources — subnets, route tables, security lists, and gateways — are automatically adjusted based on these two choices. No manual editing of security rules or route tables is needed.</p><h3>How the IaC Stack Works</h3><p>This section demonstrates the practical implementation of the proposed architecture through Infrastructure as Code. By leveraging Terraform in conjunction with Oracle Resource Manager (ORM), the entire lifecycle — from foundational networking to full OKE cluster deployment — is executed in a consistent, automated, and repeatable manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAu7Rp4ifIjHkawy-4mtgA.png" /><figcaption>Figure 3 — Terraform CLI and ORM Lifecycle: Commands, Jobs, and Actions</figcaption></figure><h4>One Stack, Four Scenarios</h4><p>Two OKE parameters are worth highlighting before diving into the code: cni_type and is_api_endpoint_public cannot be changed after cluster creation. If you need to switch between Flannel and VCN-Native, or between a public and private API endpoint, the cluster must be recreated. This is precisely where IaC shines — the ability to tear down and rebuild with a different configuration is fast, reliable, and leaves no room for manual error. Evaluating the right setup for your workload becomes an iterative exercise rather than a one-time gamble.</p><p>The stack embraces this reality by supporting all four combinations through a single codebase. Instead of maintaining separate configurations, local flags derived from input variables drive every conditional decision:</p><pre>locals {<br>  is_vcn_native  = var.cni_type == &quot;OCI_VCN_IP_NATIVE&quot;<br>  is_flannel     = var.cni_type == &quot;FLANNEL&quot;<br>  is_api_public  = var.is_api_endpoint_public<br>  is_api_private = !var.is_api_endpoint_public<br>}</pre><h4><strong>Conditional Resources</strong></h4><p>These flags determine which resources are created at all. The pods subnet, for example, only exists under VCN-Native CNI:</p><pre>module &quot;subnet-pods&quot; {<br>  count  = local.is_vcn_native ? 1 : 0<br>  source = &quot;./modules/subnet&quot;<br>  # ...<br>}</pre><p>The same applies to routing. VCN-Native worker nodes use a service-only route table — Service Gateway without NAT — because in that model it is the pods, not the nodes, that handle internet-bound traffic:</p><pre>module &quot;rt-service-only&quot; {<br>  count  = local.is_vcn_native ? 1 : 0<br>  source = &quot;./modules/route_table&quot;<br>  route_rules = [<br>    {<br>      network_entity_id = module.sg-vcn.service_gateway_id<br>      destination       = module.sg-vcn.all_region_services<br>      destination_type  = &quot;SERVICE_CIDR_BLOCK&quot;<br>    }<br>  ]<br>}</pre><h4>Dynamic Security Lists</h4><p>Security list rules differ between Flannel and VCN-Native. Instead of duplicating the entire security list definition, the stack uses concat with conditional blocks:</p><pre>ingress_security_rules = concat(<br>  # Common rules applied to all scenarios<br>  [ ... ],<br><br>  # Flannel-only: pod-to-pod communication via overlay<br>  local.is_flannel ? [<br>    {<br>      protocol    = &quot;all&quot;<br>      source      = var.subnet_nodes_cidr_24<br>      source_type = &quot;CIDR_BLOCK&quot;<br>      description = &quot;Allow pods on one worker node to communicate<br>                     with pods on other worker nodes&quot;<br>    }<br>  ] : [],<br><br>  # VCN-Native-only: worker nodes receive traffic from pods subnet<br>  local.is_vcn_native ? [<br>    {<br>      protocol    = &quot;all&quot;<br>      source      = var.subnet_pods_cidr_19<br>      source_type = &quot;CIDR_BLOCK&quot;<br>      description = &quot;Allow pods to communicate with worker nodes&quot;<br>    }<br>  ] : []<br>)</pre><p>Each scenario gets exactly the rules prescribed by the Oracle documentation — no more, no less.</p><h3>Extending the ORM Console</h3><p>Oracle Resource Manager supports a schema.yaml file that transforms the stack creation form from a flat list of raw variables into a structured, context-aware experience. This stack takes full advantage of this capability.</p><blockquote><strong>OCI Documentation:</strong> <a href="https://docs.oracle.com/en-us/iaas/Content/ResourceManager/Concepts/terraformconfigresourcemanager_topic-schema.htm">Extend Console Pages Using Schema Documents</a></blockquote><h4><strong>Variable Grouping</strong></h4><p>Instead of presenting all variables as a single list, the schema organizes them into logical sections: General Configuration, Cluster Architecture, Network Configuration, and Node Pool Configuration. Each group has a title and description that guides the operator through the decision process.</p><pre>variableGroups:<br>  - title: &quot;Cluster Architecture&quot;<br>    description: &quot;Choose the CNI plugin and API endpoint exposure<br>                   to match one of the four reference scenarios.&quot;<br>    variables:<br>      - type_of_cluster<br>      - cni_type<br>      - is_api_endpoint_public</pre><h4><strong>Dynamic Dropdowns</strong></h4><p>Several fields use OCI-native types that render as dropdowns populated directly from the tenancy — no need to copy-paste OCIDs or type values manually:</p><pre>region:<br>  type: oci:identity:region:name<br><br>compartment_id:<br>  type: oci:identity:compartment:id<br><br>ad_name:<br>  type: oci:identity:availabilitydomain:name<br>  dependsOn:<br>    compartmentId: compartment_id<br><br>kubernetes_version:<br>  type: oci:kubernetes:versions:id<br>  dependsOn:<br>    compartmentId: compartment_id<br>    clusterOptionId: cluster_option_id</pre><p>The region field lists all subscribed regions in the tenancy. The kubernetes_version field queries the OKE API via GetClusterOptions and lists only stable Kubernetes versions available in the selected region — replacing the previous free-text field where the operator had to type the version manually.</p><h4><strong>Conditional Visibility</strong></h4><p>The Pods Subnet CIDR field only appears when the CNI is set to OCI VCN-Native. When Flannel is selected, the field is hidden entirely — reducing visual noise and preventing configuration errors:</p><pre>subnet_pods_cidr_19:<br>  type: string<br>  title: &quot;Pods Subnet CIDR&quot;<br>  visible:<br>    eq:<br>      - ${cni_type}<br>      - &quot;OCI_VCN_IP_NATIVE&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QF0Gm29m1XBqxLmFfEoeQ.png" /><figcaption><em>Figure 4 — ORM form with OCI VCN-Native selected (Pods Subnet CIDR visible)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwQorgZQOp9Tf-xiemUfRA.png" /><figcaption><em>Figure 5 — ORM form with Flannel selected (Pods Subnet CIDR hidden)</em></figcaption></figure><p>This conditional behavior is the bridge between the IaC stack and the operator’s experience — the same logic that drives count in Terraform also drives what the operator sees in the console.</p><h3>Scope and Considerations</h3><p>This implementation targets OKE-managed node pools using Oracle Linux 8 as the worker node operating system. The automatic image resolution in data.tf filters exclusively for OKE Oracle Linux 8 images (x86_64), excluding ARM (aarch64) and GPU (Gen2-GPU) variants.</p><p>The following deployment models are not covered by this stack:</p><ul><li>Virtual node pools (serverless)</li><li>Self-managed worker nodes (instance pools)</li><li>Custom images or Oracle Linux 7</li></ul><p>These constraints reflect a deliberate design choice: the stack focuses on the most common production pattern — managed node pools with Oracle Linux 8 — aligned with the reference architectures in the Oracle documentation.</p><h3>Deploying the Stack</h3><p>The deployment workflow through Oracle Resource Manager consists of five steps. For complete instructions, screenshots, and variable reference, see the <a href="https://github.com/jefersonferr/oke-cluster-tf/blob/master/oci-deployment.md"><strong>deployment guide</strong></a> in the repository.</p><p><strong>Step 1 — Create the Stack.</strong> Navigate to Developer Services → Resource Manager → Stacks and create a new stack. Import the Terraform configuration by uploading a ZIP file downloaded from the repository, or by connecting a GitHub Source Provider directly to your fork. Once uploaded, ORM automatically parses the schema.yaml file and populates the stack title, description, and supported scenarios.</p><p><strong>Step 2 — Configure Variables.</strong> ORM renders schema.yaml as a guided form organized into four sections: General Configuration, Cluster Architecture, Network Configuration, and Node Pool Configuration. The General Configuration section uses OCI-native dropdowns for Region, Compartment, Availability Domain, and Kubernetes Version — all populated directly from the tenancy and OKE API, with no OCIDs to copy or version strings to look up manually. In the Cluster Architecture section, select your CNI plugin and API endpoint exposure. The form adapts automatically: the Pods Subnet CIDR field appears only when OCI VCN-Native is selected, and is hidden entirely when Flannel is chosen.</p><p><strong>Step 3 — Plan.</strong> Run Terraform Actions → Plan to preview all resources before anything is created. The number of resources varies by scenario: Flannel produces approximately 15 resources, VCN-Native approximately 18, reflecting the additional pod subnet, its security list, and the service-only route table. The plan output includes a scenario_description value confirming which Oracle reference architecture was selected.</p><p><strong>Step 4 — Apply.</strong> Run <strong>Terraform Actions → Apply</strong>. Typical provisioning time is 10 to 15 minutes. The Node Image OCID field is optional — if left empty, the stack automatically resolves the latest OKE Oracle Linux 8 image compatible with the selected Kubernetes version and region. This is handled by the oci_containerengine_node_pool_option data source, which queries the OKE API at plan time and returns the available node images for the selected region and Kubernetes version — the same list you would browse manually in the Oracle documentation to find a valid image OCID. The resolved image OCID is exposed as an output after apply, so you can always verify exactly which image was used. After completion, the Outputs tab confirms the cluster ID, VCN and subnet IDs, the effective node image used, and the scenario description.</p><p><strong>Step 5 — Validate.</strong> Navigate to Developer Services → Kubernetes Clusters (OKE) and confirm the cluster is in ACTIVE state. Connect via Cloud Shell and run kubectl get nodes to verify that worker nodes are in Ready status.</p><h3>Why IaC — Concrete Benefits for OKE</h3><p>This integrated approach simplifies complex provisioning workflows while ensuring that best practices and reference architecture guidelines are systematically enforced. Consequently, teams can transition from design to production with increased speed, reliability, and architectural control.</p><p>Beyond the general advantages of IaC, this stack delivers benefits that are specific to the OKE and ORM context:</p><h4><strong>Drift Detection</strong></h4><p>Unlike Quick Create, where the console has no record of the intended state, ORM maintains the full Terraform state for every stack. If someone manually changes a security list rule or modifies a route table through the console, the divergence can be surfaced at any time using the check-drift option under Terraform Actions — no need to remember to run terraform plan manually. The next plan jobthen shows exactly what a terraform apply would do to reconcile it.</p><h4><strong>Scenario Switching</strong></h4><p>Migrating from Flannel to VCN-Native CNI, or from a public to a private API endpoint, typically requires tearing down and rebuilding the entire network stack manually. With this IaC approach, it is a matter of changing one or two variables and running a single apply job<strong>.</strong> The stack handles the creation and removal of conditional resources automatically — and even when a change requires resource destruction, IaC ensures this is handled safely and predictably, orchestrating the destroy-before-createlogic with speed and precision.</p><h4><strong>Customization Without Leaving the Console</strong></h4><p>The stack is a starting point, not a ceiling. The recommended way to use this repository is to fork it into your own GitHub account, create a Source Provider in Oracle Resource Manager pointing to that fork, and create the stack from a Source Code Control System instead of a zip upload. This keeps the infrastructure state and the code history traceable together — every job apply has a corresponding commit in the fork.</p><blockquote>For step-by-step instructions on creating a stack from the Source Provider — GitHub, see <a href="https://github.com/jefersonferr/oke-cluster-tf/blob/master/oci-deployment.md">Deployment Instructions</a> from repository.</blockquote><p>From there, Oracle Resource Manager includes a built-in Code Editor that allows direct modifications to the Terraform files from within the OCI Console — no local toolchain required. As shown in Figure 6, a new ingress rule can be added directly to the pods security list — no local toolchain, no manual console edits, no risk of drift. The change can be planned, reviewed, and applied in minutes, with ORM maintaining state consistency throughout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YmF3orN_mxp66eQ2uJJ2w.png" /><figcaption><em>Figure 6 — ORM Code Editor: adding a new ingress rule to the pods security list</em></figcaption></figure><p>Edits made through the Code Editor can be committed back to the fork via Git, turning a one-off adjustment into a versioned, reusable configuration. Promoting a customization from one environment to another — say, from Staging to Production — becomes a matter of pointing a new stack at the same repository. The customization travels with the code, not with the person who made it. The public repository serves as the upstream template; all customization happens in the fork, never directly on the source.</p><h3>Conclusion</h3><p>Provisioning an OKE cluster should not force a choice between simplicity and control. Quick Create is fast but inflexible. Custom Create is powerful but manual and error-prone. The IaC stack presented in this article eliminates this trade-off by encoding all four Oracle reference networking scenarios into a single, parameterized Terraform configuration — and extending the ORM Console with a schema that adapts to the operator’s choices. The result is the one-click experience of Quick Create with the architectural precision of Custom Create, backed by version control, drift detection, and full reproducibility.</p><h4><strong>Choosing Your Starting Scenario</strong></h4><p>If you are unsure which of the four scenarios to start with, the following table maps common environment profiles to the recommended configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VF61-zwHnqo2NMvi10PuA.png" /><figcaption><em>Figure 7 — </em>OKE Network Architecture Decision Guide</figcaption></figure><p>A practical starting point for most teams is Example 1 — it minimizes initial complexity and lets you validate the stack and the ORM workflow before committing to a more constrained architecture. Once the cluster is running and the team is comfortable with the IaC lifecycle, migrating to Example 4 is a matter of changing two variables and rebuilding — which is precisely what this stack is designed for.</p><p>The complete implementation is open-source and ready to use:<a href="https://github.com/jefersonferr/oke-cluster-tf"> github.com/jefersonferr/oke-cluster-tf</a>. Contributions, issues, and feedback are welcome.</p><h3><strong>About the Author</strong></h3><p><strong>Jeferson Ferreira</strong> is a Cloud Solutions Architect with hands-on experience designing and implementing cloud-native infrastructures. He holds multiple Oracle Cloud Infrastructure professional certifications — including Architect, Migration Architect, Multicloud Architect, Autonomous Database, and Generative AI — as well as the GCP Professional Cloud Architect certification. His work focuses on Infrastructure as Code, Kubernetes, DevOps, and building scalable, production-grade cloud environments.</p><blockquote><a href="https://www.linkedin.com/in/jefersonferr">LinkedIn</a> · <a href="https://github.com/jefersonferr">GitHub</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ba4ce75dc52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Manual to Scalable: Leveraging IaC to Build Secure, Cost-Efficient Cloud Infrastructure on OCI]]></title>
            <link>https://medium.com/@jefersonferr/terraform-on-oci-a-practical-guide-to-highly-available-secure-and-cost-efficient-infrastructure-cebe4d1fcf5c?source=rss-6752562df90b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cebe4d1fcf5c</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[oraclecloudinfrastructure]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Jeferson Ferreira]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 18:30:20 GMT</pubDate>
            <atom:updated>2026-03-26T20:35:12.638Z</atom:updated>
            <content:encoded><![CDATA[<h4>A beginner-friendly demonstration of how Infrastructure as Code can simplify your day-to-day cloud operations on Oracle Cloud Infrastructure — and why you should start using it today.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB_AONr192naM7ytT8Su9A.png" /><figcaption>Image generated with ChatGPT</figcaption></figure><h3>Overview</h3><p>Managing cloud infrastructure manually introduces significant risks: configuration inconsistencies, lack of traceability, and slow provisioning cycles that hinder organizational agility. This article addresses these challenges by demonstrating the implementation of a resilient and secure architecture on Oracle Cloud Infrastructure (OCI) using Terraform.</p><p>The primary focus is to illustrate how Infrastructure as Code (IaC) serves as the foundation for operational agility, security compliance, and cost reduction — showcasing practical skills aligned with real-world enterprise requirements.</p><h3>Architecture Highlights</h3><p>The architecture is designed around four core pillars:</p><ul><li><strong>Virtual Cloud Network (VCN)</strong> with public and private subnets for traffic isolation, route tables, and gateways</li><li><strong>High Availability</strong> through distribution of compute instances across Availability Domains and Fault Domains</li><li><strong>OCI Load Balancer</strong> to distribute traffic across web server compute instances with integrated health checks</li><li><strong>Layered security</strong> using Security Lists, Network Security Groups (NSGs), and Bastion for controlled administrative access</li></ul><blockquote>As illustrated in Figure 1, traffic flows from the internet through the Load Balancer (hosted in the public subnet) reaching three web servers — WebServer01, WebServer02, and WebServer03 — distributed across Fault Domains in the private subnet, while the Bastion Host provides the sole administrative entry point.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*5TLeEA9wDWdNIxeZHB50KA.png" /><figcaption><strong><em>Figure 1 — Architecture.</em></strong><em> OCI Region with a VCN containing three subnets: Public A (hosting the Load Balancer), Public B (hosting the Bastion Host), and Private C (hosting three web servers distributed across Fault Domains 1, 2, and 3 within Availability Domain 1). Internet access is provided via an Internet Gateway.</em></figcaption></figure><h3>Terraform &amp; Automation Approach</h3><p>The infrastructure was fully automated using Terraform, following three core best practices:</p><h4>Modular Design to Improve Reuse and Maintainability</h4><p>In Terraform, modules organize and encapsulate related resources and configurations into reusable, shareable components. By breaking infrastructure code into smaller, manageable units — as illustrated in Figure 2 — teams can promote reusability, maintainability, and collaboration, avoiding duplication across projects and environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*_7_r5WK2xzM1rbv7Sdhztg.png" /><figcaption><strong><em>Figure 2 — Terraform Modules.</em></strong><em> Project structure showing the root </em><em>main.tf and </em><em>output.tf, alongside three child modules — </em><em>bastion, </em><em>network, and </em><em>webservers — each containing their own </em><em>main.tf, </em><em>output.tf, and </em><em>variables.tf files, promoting separation of concerns and independent reuse.</em></figcaption></figure><h4>Controlled State Management to Ensure Consistency and Reliability</h4><p>Terraform’s state management tracks real-world resources against their declared configuration. Using centralized remote backends with locking and versioning — such as OCI Object Storage — ensures consistency across deployments, prevents concurrent modification conflicts, and improves reliability when multiple users or pipelines interact with the same infrastructure.</p><p>Code Snippets 1 and 2 illustrate how infrastructure components are declaratively defined using Terraform’s HCL syntax, reinforcing the concept of desired state configuration. Code Snippet 1 shows the module invocation in main.tf, where parameters such as compartment IDs, subnet IDs, Bastion IP, and SSH keys are explicitly mapped to the webservers module. Code Snippet 2 shows the corresponding variable definitions in terraform.tfvars, where each web server&#39;s specifications are individually declared.</p><pre>&gt; main.tf<br><br>#Define the module and its Parameters<br>module &quot;webservers&quot; {<br>  source            = &quot;./modules/webservers&quot;     #Webserver module location<br>  compartment_ids   = var.compartment_ids        #Compartment IDs<br>  subnet_ids        = module.network.subnets_ids #Subnet IDs<br>  bastions_ip       = module.bastion.bastion_ip  #Bastion IP<br>  webservers_params = var.webservers_params      #Webservers Parameters<br>  linux_images      = var.linux_images           #Webservers Image<br>  region            = var.provider_oci.region #Webservers region location<br>  ssh_keys          = var.ssh_keys            #SSH key pairs for Webservers<br>}</pre><p><strong><em>Code Snippet 1— Module invocation with parameter mapping (main.tf).</em></strong><em> The </em><em>webservers module block in </em><em>main.tf with explicit parameter mapping, including </em><em>compartment_ids, </em><em>subnet_ids, </em><em>bastions_ip, </em><em>webservers_params, </em><em>linux_images, OCI region, and </em><em>ssh_keys — demonstrating how the root module delegates resource creation to a child module with full parameterization</em></p><pre>&gt; terraform.tfvars<br><br>#----------- Webservers Specifications -----------------------------<br>webservers_params = {<br>  webserver01 = {<br>    compartment_data     = &quot;comp-ocid&quot;<br>    subnet_name          = &quot;pub-subnet-oci-WebBastion-vcn&quot;<br>    ssh_public_key       = &quot;ssh_public_key&quot;<br>    ssh_private_key      = &quot;ssh_private_key&quot;<br>    webserver_data       = &quot;webserver01&quot;<br>    display_name         = &quot;webserver01&quot;<br>    shape                = &quot;VM.Standard2.1&quot;<br>    version              = &quot;sa-saopaulo-oel7&quot;<br>    ad                   = 1<br>    fault_domain         = 1<br>    boot_volume_size     = 50<br>    preserve_boot_volume = false<br>    assign_public_ip     = false<br>    freeform_tags        = {}<br>  }<br>  webserver02 = {<br>    compartment_data     = &quot;comp-ocid&quot;<br>    subnet_name          = &quot;pub-subnet-oci-WebBastion-vcn&quot;<br>    ssh_public_key       = &quot;ssh_public_key&quot;<br>    ssh_private_key      = &quot;ssh_private_key&quot;<br>    webserver_data       = &quot;webserver02&quot;<br>    display_name         = &quot;webserver02&quot;<br>    shape                = &quot;VM.Standard2.1&quot;<br>    version              = &quot;sa-saopaulo-oel7&quot;<br>    ad                   = 1<br>    fault_domain         = 2<br>    boot_volume_size     = 50<br>    preserve_boot_volume = false<br>    assign_public_ip     = false<br>    freeform_tags        = {}<br>  }<br>  webserver03 = {<br>    compartment_data     = &quot;comp-ocid&quot;<br>    subnet_name          = &quot;pub-subnet-oci-WebBastion-vcn&quot;<br>    ssh_public_key       = &quot;ssh_public_key&quot;<br>    ssh_private_key      = &quot;ssh_private_key&quot;<br>    webserver_data       = &quot;webserver03&quot;<br>    display_name         = &quot;webserver03&quot;<br>    shape                = &quot;VM.Standard2.1&quot;<br>    version              = &quot;sa-saopaulo-oel7&quot;<br>    ad                   = 1<br>    fault_domain         = 3<br>    boot_volume_size     = 50<br>    preserve_boot_volume = false<br>    assign_public_ip     = false<br>    freeform_tags        = {}<br>  }<br>}</pre><p><strong><em>Code Snippet 2 — Variables definitions for specifications (terraform.tfvars).</em></strong><em> </em>Each web server is assigned to a different fault domain (fault_domain = 1, 2, and 3), ensuring that a failure in one does not affect the others — the key configuration behind High Availability. Additionally, assign_public_ip = false keeps all instances off the public internet.</p><h4>Standard Terraform Workflow: init, plan, apply, and destroy</h4><p>The standard Terraform lifecycle provides a clear and repeatable process for infrastructure provisioning:</p><ul><li>init — initializes the working directory and configures providers and backends</li><li>plan — generates a preview of all changes before they are applied, enabling safe review</li><li>apply — executes the planned changes to provision or update resources</li><li>destroy — safely removes managed infrastructure when no longer needed</li></ul><p>This workflow promotes transparency, control, and auditability at every stage of the infrastructure lifecycle. Figure 3 illustrates this lifecycle visually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*jGkSsto_Ueywm6pwSJwq2w.png" /><figcaption><strong><em>Figure 3— Terraform Workflow.</em></strong><em> A cyclical diagram showing the four stages of the standard lifecycle: </em><em>init → </em><em>plan → </em><em>apply → </em><em>destroy. The &quot;Update code&quot; arrow feeds back into </em><em>plan, while &quot;Deploy infra&quot; represents the outcome of </em><em>apply — illustrating the iterative and controlled nature of IaC-based provisioning.</em></figcaption></figure><h3>Why Infrastructure as Code Matters</h3><p>Manual infrastructure management is inherently fragile — prone to undocumented changes, inconsistent environments, and slow recovery when failures occur. Infrastructure as Code addresses these risks by introducing determinism and traceability into environment management. Every change becomes versioned, reviewable, and auditable, significantly reducing operational risk and human error.</p><p>In enterprise environments, this approach enables the consistent application of architectural standards, security controls, and compliance requirements across multiple projects, teams, and regions — ensuring that infrastructure evolves in a controlled, governable manner.</p><blockquote>Another critical benefit is the reduction of configuration drift. By continuously comparing the desired state of the infrastructure with its actual state, unplanned deviations can be quickly identified and remediated — making environments more predictable and reliable while simplifying troubleshooting and recovery processes, as demonstrated in Figure 4.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*1fT-0Cv2j7_85Od1a1oi9w.png" /><figcaption><strong><em>Figure 4— Terraform Plan action.</em></strong><em> The execution plan output showing 27 resources to be added, with planned outputs including </em><em>bastion_ip, three network subnets (</em><em>priv-subnet-oci-WebApps-vcn, </em><em>pub-subnet-oci-WebBastion-vcn, </em><em>pub-subnet-oci-WebLB-vcn), the VCN (</em><em>oci-WebApps-vcn with CIDR </em><em>10.0.0.0/16), and the three web server IPs — all marked as &quot;known after apply&quot;. This output allows operators to validate every planned change before execution, preventing unintended modifications.</em></figcaption></figure><h3>FinOps Perspective</h3><p>The technical benefits of IaC translate directly into financial value. From a FinOps standpoint, treating infrastructure as code enables more disciplined and efficient cloud spending across three dimensions:</p><h4>Rapid Provisioning and Teardown of Ephemeral Environments</h4><p>Infrastructure as Code enables the fast creation and decommissioning of proof-of-concept and temporary environments through automated workflows. This minimizes the risk of leaving idle resources running, directly reducing unnecessary cloud spending and improving cost efficiency.</p><h4>Dynamic Resource Sizing Aligned with Workload Demand</h4><p>By defining infrastructure through code and parameterized variables, IaC allows resources to be sized and adjusted according to actual workload requirements. This flexibility prevents overprovisioning, ensures optimal utilization of cloud services, and aligns infrastructure costs with real business demand.</p><h4>Reduced Operational Effort, Lowering Costs and Accelerating Time-to-Market</h4><p>Automation through IaC reduces manual intervention in infrastructure provisioning and management. This lowers operational and engineering costs while accelerating deployment cycles — enabling teams to deliver features and environments faster without sacrificing financial discipline.</p><h3>Conclusion</h3><p>This implementation demonstrates that when infrastructure is treated as code, it evolves from a purely operational necessity into a strategic business capability. By leveraging automation, modular design, and controlled state management, organizations can build scalable, secure, and cost-efficient cloud environments while maintaining consistency across deployments.</p><p>Automation enables environments to scale predictably, security controls to be embedded by design, and governance to be enforced without compromising agility. At the same time, the standardization promoted by IaC reduces configuration drift, strengthens compliance, and enhances financial predictability.</p><p>Beyond technical implementation, Infrastructure as Code establishes a solid foundation for advanced operational practices such as DevSecOps, FinOps, and automated disaster recovery. By aligning engineering efficiency with governance and cost management, IaC becomes more than a provisioning approach — it becomes a foundational discipline for achieving operational excellence, organizational maturity, and long-term cloud sustainability.</p><p>A special thanks to Claude (Anthropic) for the editorial review — helping sharpen the structure, clarity, and technical precision of this article, while all ideas, architecture decisions, and technical content are entirely my own.</p><blockquote>If you already have some experience with Terraform, feel free to download the <a href="https://livelabs.oracle.com/cdn/oci/terraform-infrastructure/setup/files/skeleton.zip">Terraform Template</a> and explore the code at your own pace. If you’d like to learn Terraform hands-on using this exact architecture, Oracle offers a guided workshop through LiveLabs — access it <a href="https://livelabs.oracle.com/ords/r/dbpm/livelabs/view-workshop?wid=3834">here</a> and follow the step-by-step instructions to deploy the full environment yourself.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cebe4d1fcf5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>