Oracle 26ai Raft Replication vs CockroachDB: Resilience Tested by Crashing the Leader

Oracle 26ai Raft replication vs CockroachDB: write pause 0.34–0.79 s vs 3.8–4.4 s after a leader crash, 0 commits lost on both

Oracle Database 26ai and CockroachDB look like opposites. One is the classic enterprise database, the other a cloud-native distributed SQL engine. Yet for high availability they now rely on the same idea: the Raft consensus protocol. In Oracle Globally Distributed Database, Raft replication is built into the database itself: no Data Guard and no GoldenGate between the shards. CockroachDB has used Raft for every range of data from day one.

I work with both, so I wanted to see the difference in practice, not on a slide. I built the same test on each: one session commits nonstop, and I crash the node holding the leader in the middle of it. Then I measured how long writes paused, whether any committed data was lost, what the application saw, and what happened when the node came back. This post explains both architectures with animations and shows every measured number. Both test kits are at the end.

TL;DR
  • Same guarantee: neither database lost a single acknowledged commit, in 6 leader crashes (0 of 124,911 on Oracle and 0 of 382,491 on CockroachDB).
  • Different failover speed: writes paused for 0.34–0.79 s on Oracle 26ai (client reconnected to the new leader through the shard directors) and 3.8–4.4 s on CockroachDB (the gateway waited for the old lease to expire), both with default settings.
  • The lesson for every application: on both, the transaction in flight during the crash returned an error, and in 1 of 3 runs on each it had actually committed. A blind retry would have created a duplicate.
  • Coming back: CockroachDB moved the leader back on its own (77–113 s later, pause under 0.1 s). Oracle keeps the new leader until you run gdsctl switchover ru -rebalance (pause 0.28–0.51 s).
  • Plus four things I only learned by doing it, from the 100,000-change transaction limit to why "Ok" does not mean "caught up".
Animated side-by-side walkthrough of Raft in Oracle 26ai and CockroachDB: write commit on a majority, leader crash, new leader election and node recovery


Key terms used in this post
Raft leader / follower
For each piece of data, one copy (the leader) takes the writes and sends them to the other copies (the followers).
Term
A Raft election counter. It goes up by one every time a new leader is elected, so a higher term means a failover happened.
Sharding key, chunk, replication unit (RU)
Oracle: the sharding key (here the customer id) decides which chunk a row belongs to; chunks are grouped into RUs, and each RU has its own Raft leader.
Range, leaseholder
CockroachDB: data is split into ranges; the leaseholder is the copy that serves a range's reads and writes, normally the Raft leader.
Commit in doubt
A COMMIT that failed with a lost-connection error: the client cannot tell whether it was saved. It may have been.

Raft in one minute

Raft keeps several copies (replicas) of the same data in agreement. For each piece of data, one replica is the leader and the others are followers. Every change goes to the leader, which writes it to its Raft log and sends it to the followers. As soon as a majority (2 of 3) has it in their logs, the change is committed and the client gets its answer. If the leader stops sending heartbeats, the followers hold an election, one of them becomes the new leader, and the term number goes up by one. Because a majority always has every committed change, the new leader has them all: that is why nothing committed is lost.

Two architectures built on Raft

The protocol is the same; the way each product wraps it is very different. This is the part that matters for design decisions:

Oracle Globally Distributed Database (26ai), Raft replicationCockroachDB
Unit of replicationReplication unit (RU): a set of chunks (table partitions). The number of RUs is set at deployment.Range: a slice of the key space (up to about 512 MB by default) that splits and merges automatically.
Who takes the writesThe RU leader. Leaders are spread: in my sandbox (3 shards, 6 RUs) each shard led 2 RUs and followed 4.The range leaseholder, normally the Raft leader.
Commit ruleThe leader plus half of the followers have the commit record in their Raft log. The Raft log is logical and separate from redo; followers apply the changes asynchronously.A majority of replicas have the write in their Raft log.
Replication factor3 (the documentation describes RF 3)3 by default; 5 or more per database or table
How the client finds the leaderShard directors (GSM) route each new session by sharding key to the right leader; the session then talks to that shard directly. A shard catalog holds the metadata.The client connects to any node; that node (the gateway) forwards each request to the right leaseholder.
Data modelYou design it: sharded tables with a sharding key, table families (PARTITION BY REFERENCE), duplicated tables for small reference data.Automatic: every table is distributed by its primary key; no sharding key to choose.
Rebalancing leadersExplicit: gdsctl switchover ru -rebalance, move ru, relocate chunkAutomatic, steered by zone configuration (for example lease preferences)
Oracle's own failover target"Sub-3 seconds" with under 10 ms between availability zones (documentation)(measured below)
What you keepFull Oracle SQL, PL/SQL and the Oracle tool chain, with control over where every customer's data livesPostgreSQL wire protocol, very simple operations, no router tier

The two deployments I tested

Here is what each setup looked like. On the Oracle side, the shard catalog holds the map of the whole system and pushes DDL to every shard, and two shard directors route each new session by its sharding key to the shard that leads the right replication unit; after that, the session talks to that shard directly. Each of the 3 shards is a normal Oracle 26ai database (a CDB with one PDB) that leads 2 replication units and holds follower copies of 4 more, so all three do write work and none is an idle standby. On the CockroachDB side there is no catalog and no router: every node is a SQL gateway, stores data and holds replicas, and the gateway forwards each write to the node holding the lease for that range.

Tested deployments: Oracle 26ai with shard catalog, two shard directors and three shards leading two replication units each, next to a three-node CockroachDB cluster with no router tier

Think of the Oracle design as three databases that are each partly primary and partly standby at the same time, with Raft inside the database doing the work Data Guard would otherwise do.

The test: the same crash on both

I wanted a test that is easy to explain and hard to argue with. One application session commits small transactions nonstop, each with a unique number. In the middle of it, the node that holds the leader for that data is crashed. Afterwards, every number the client saw acknowledged must be in the table.

Test caseWhat happensWhat is measured
TC1 Leader crash under loadWriter runs 20 s, then the leader's node is killed: kill -9 of the CockroachDB process; shutdown abort of the Oracle shard, which in this sandbox also stopped the whole shard containerLongest gap between two acknowledged commits; errors seen by the client; where it reconnected
TC2 No data lossAfter each run, every acknowledged number is looked up in the tableAcknowledged commits missing from the table
TC3 Commit in doubtFor the transaction that failed during COMMIT, check whether it really committedReal outcome of each in-doubt commit
TC4 Node comes backRestart the node, wait until it has caught up, then move the leader back (automatically on CockroachDB, gdsctl switchover ru -rebalance on Oracle) while a writer runsCatch-up, and the write pause during the planned leader move
Oracle 26aiCockroachDB
Version23.26.3.0.0 (Oracle AI Database 26ai), Globally Distributed Database with native Raft replicationv26.2.0
WhereOracle LiveLabs sandbox "Use Raft Replication with Distributed Database for Resilient Never-Down Apps": shard catalog, 2 shard directors, 3 shards in containers3 nodes on my RHEL 8 test server (16 vCPUs, 62 GB RAM), local only
ReplicationRF 3, 6 replication units, leaders balanced (2 per shard)RF 3, the test table's lease pinned to node 3
ClientJava 17, JDBC thin driver, connected through the shard directors with the customer id as sharding keypsql, connected to node 1 (so the gateway survives the crash)
WorkloadOne INSERT + COMMIT at a time into Orders for one customer (≈ 550 per second)One INSERT + COMMIT at a time (≈ 750 per second)
Runs3, each crashing the shard that led the customer's RU3, each crashing node 3

Results

Bar chart of write pauses in 3 runs each: Oracle 26ai 0.34–0.79 s and CockroachDB 3.8–4.4 s after a leader crash; leader moving back 283–508 ms on Oracle and 33–79 ms on CockroachDB


RunOracle: write pause after crashOracle: commits acked / lostCockroachDB: write pause after crashCockroachDB: commits acked / lost
10.79 s48,687 / 04.43 s143,577 / 0
20.34 s38,548 / 03.79 s132,217 / 0
30.42 s37,676 / 03.79 s106,697 / 0

What the Oracle client saw, second by second

The Oracle sequence was the same in all three runs (times from run 1, measured from the shutdown abort command):

+0.40 s  COMMIT fails      ORA-17410: No more data to read from socket   <- the in-doubt transaction
+0.43 s  reconnect         ORA-12523: TNS:listener could not find instance appropriate
         ... retried every 0.1 s, 5 times: the shard director still pointed at the dead shard
+1.03 s  connected         to ORCL2PDB, the new leader of RU 3
         writes continue;  longest gap between two commits: 0.79 s

That is the shard director tier doing its job: as soon as the new leader was registered, the next connection attempt went straight to it. In runs 2 and 3 the client was back after 0.73 and 0.82 s. On CockroachDB the client never lost its connection: the gateway (node 1) stayed up, and its statements simply waited until the lease for the range had moved to a surviving node, about 3.8 s with default settings.

Oracle LiveLabs Raft dashboard before and after crashing Shard3: replication unit 3 leader moves from Shard3 to Shard1, term 13 to 14, Shard3 shown as down

The most important finding: the commit in doubt

Both databases behaved correctly, and both left the application with the same hard question. The transaction that was committing at the moment of the crash came back with an error: ORA-17410 on Oracle, SQLSTATE 40003 result is ambiguous on CockroachDB. Did it commit or not? I checked every one of them:

EventError the client gotDid it actually commit?
Oracle, crash run 1ORA-17410 during COMMITYes
Oracle, crash runs 2 and 3ORA-17410 during COMMITNo
Oracle, planned switchover run 2ORA-17410 during COMMITYes
Oracle, planned switchover run 3ORA-17410 during COMMITNo
Oracle, planned switchover run 1ORA-03974 on INSERT: cannot perform DML operations during switchover … for replication unit 3No (rejected cleanly before commit)
CockroachDB, runs 1 and 2SQLSTATE 40003 during COMMITNo
CockroachDB, run 3SQLSTATE 40003 during COMMITYes

Both outcomes are correct Raft behaviour, and the animation shows why. If the leader dies before a majority has the commit, it is lost with the leader and rolled back. If it dies after a majority has it but before it can answer, the commit is durable on the new leader, but the client only saw a broken connection.

Animated sequence diagram showing why a commit can be in doubt when the Raft leader crashes: rolled back in one case, committed despite an error in the other

What this means for your application: a "connection lost during COMMIT" error does not mean "not committed". In banking terms, a blind retry of a payment can book it twice. Give every business transaction its own key, generated by the client, and after an in-doubt error check for that key before retrying, or make the write idempotent with MERGE / UPSERT on it. On Oracle, Transaction Guard is designed to return the commit outcome of a lost session; I have not yet tested it together with Raft replication, so check it in your setup before relying on it.
-- the safe retry pattern (works on both): the client generates order_ref
INSERT INTO orders (order_ref, cust_id, amount) VALUES (:ref, :cust, :amt);
COMMIT;                     -- fails with ORA-17410 / SQLSTATE 40003?

-- reconnect, then:
SELECT count(*) FROM orders WHERE order_ref = :ref;
-- 1 -> it was committed: do NOT insert again
-- 0 -> it was not: retry the transaction

Coming back: catch-up and moving the leader back

Catch-up. On Oracle, the restarted shard was a follower again and fully caught up (identical log index on all three replicas) about 4 s after its container reported healthy. In one longer outage during my preparation, a shard that was about 1.7 million log entries behind caught up in under 6 minutes. On CockroachDB the restarted node also rejoined as a follower without any action.

Leadership. Here the two designs differ clearly:

  • CockroachDB moved the lease back to node 3 on its own (because of the lease preference I had set), 77–113 s after the restart. The write pause during that move was 33–79 ms.
  • Oracle keeps the new leader where it is. Until you act, the surviving shards carry the extra leaders: after the first crash, Shard1 led 4 of the 6 RUs. gdsctl switchover ru -rebalance spread them again in about 5 s; the write pause was 0.28–0.51 s, and new DML during the switch got a clean ORA-03974.

Neither is better in general. Automatic is less work; explicit gives the DBA control over when leaders move, which many banking teams prefer during business hours.

Four things I only learned by doing it

  1. Raft transactions have a size limit. Cleaning up 1.7 million test rows in one DELETE failed with ORA-05109: Transaction is too large for sharding native replication. Maximum allowed size is 100000. Batch large deletes and updates (I used 50,000 rows per commit).
  2. "Ok" does not mean "caught up". Right after a restart, gdsctl status ru showed the returning shard as Ok while its log index was still 615,000 entries behind the leader. Compare the Log Index column before you call a shard healthy.
  3. Reconnects need retries. For a fraction of a second after the crash, the shard directors still routed to the dead shard (ORA-12523). A connection pool or retry loop with a short delay handles it; a single attempt would have failed.
  4. CockroachDB v26.2 hides its internal tables. Queries on crdb_internal now fail unless you set allow_unsafe_internals; use the supported commands (cockroach node status, SHOW RANGES ... WITH DETAILS). And a lease preference needs constraints = '[]' in the same zone configuration.

Which one, when?

  • Choose Oracle Globally Distributed Database with Raft when you already run Oracle, need the full Oracle feature set, and want to decide yourself which customers' data lives where (data sovereignty, regional regulations). Expect to design the sharding key and table families, and to own leader placement as an operational task. In my test it failed over fastest.
  • Choose CockroachDB when you want a distributed database that needs almost no data-placement design and rebalances itself, and your application fits the PostgreSQL dialect. Plan for a few seconds of write pause on a node failure with default settings.
  • Either way, make your application handle the commit in doubt. That is not a weakness of one product; it is how consensus works.

What this test does and does not show

  • It shows the failover behaviour of each database with default settings, measured the same way, with zero acknowledged commits lost in all 6 crashes.
  • The two labs ran on different infrastructure (an Oracle LiveLabs sandbox vs my test server), with different clients (Java vs psql). Compare the behaviour and the order of magnitude, not throughput.
  • All replicas were in one location. Across availability zones or regions, network latency adds to every commit and to failover on both.
  • The crash scopes differ slightly: on Oracle the whole shard container went down, on CockroachDB one database process. Both are hard crashes of the node holding the leader.
  • CockroachDB's failover time depends on its lease settings, which can be tuned; I did not tune either database.
  • Three runs each, synthetic data, one writing session. Real applications with many sessions and connection pools will see the same mechanisms at a larger scale.

How to repeat both tests

CockroachDB (any Linux server, about 5 minutes)

The kit downloads CockroachDB into /var/tmp/raftlab, starts 3 local nodes on their own ports (127.0.0.1 only, never touching an existing cluster), runs 3 crash runs and prints the summary. No root needed.

cd /var/tmp && mkdir raftkit && tar xzf raftlab_kit.tgz -C raftkit && cd raftkit/kit && chmod +x *.sh
nohup ./run_all.sh > run_all.log 2>&1 &
tail -f run_all.log                     # summary at the end
./99_cleanup.sh                         # stop and remove the 3 test nodes
README.md: how to run it
# CockroachDB leader-failover test (3 local nodes, RF 3)

Kills the node that holds the lease (the Raft leader) of a table in the middle of
a continuous write workload, and measures how long writes pause and whether any
acknowledged commit is lost. Then restarts the node and measures the lease moving back.
Synthetic data, local-only (127.0.0.1), insecure test mode: never use on a real cluster.

Needs: ~2 GB free in /var/tmp, psql (any version), perl or date. No root.

    cd /var/tmp && tar xzf raftlab_kit.tgz && cd kit && chmod +x *.sh
    nohup ./run_all.sh > run_all.log 2>&1 &      # about 5 minutes
    tail -f run_all.log
    cat /var/tmp/raftlab_results/summary.txt
    tar czf /var/tmp/raftlab_results.tgz -C /var/tmp raftlab_results
    ./99_cleanup.sh

If the server cannot download from binaries.cockroachdb.com, copy
cockroach-v26.2.0.linux-amd64.tgz to /var/tmp/raftlab/ first.
00_env.sh: settings
#!/bin/bash
# 00_env.sh : settings for the CockroachDB leader-failover test (3 local nodes, RF 3)
export CRDB_VERSION=${CRDB_VERSION:-v26.2.0}
export BASE=${BASE:-/var/tmp/raftlab}              # node stores + binary (~2 GB free needed)
export RESULTS=${RESULTS:-/var/tmp/raftlab_results}
export BIN=$BASE/bin/cockroach
export PSQL=${PSQL:-$(command -v psql || echo /usr/pgsql-18/bin/psql)}
export RUNS=${RUNS:-3}          # failover runs; each kills the leaseholder node once
export WARMUP=${WARMUP:-20}     # seconds of writes before the kill
export DOWN=${DOWN:-40}         # seconds the node stays down
sqlport()  { echo $((26260 + $1)); }    # node 1..3 -> 26261..26263 (local only)
httpport() { echo $((8090 + $1)); }     # node 1..3 -> 8091..8093 (DB Console)
csql()     { "$BIN" sql --insecure --host=127.0.0.1:$(sqlport ${NODE:-1}) "$@"; }
now()      { date +%s.%N; }
# timestamp every line of stdin as "line,epoch_seconds" (microseconds)
stamp() {
  if command -v perl >/dev/null; then
    perl -MTime::HiRes=time -ne 'BEGIN{$|=1} chomp; printf "%s,%.6f\n", $_, time'
  else
    while read -r s; do echo "$s,$(date +%s.%N)"; done
  fi
}
02_start_cluster.sh: 3 nodes, RF 3, lease on node 3
#!/bin/bash
# 02_start_cluster.sh : 3 nodes on this server (zones z1, z2, z3), RF 3, test table
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
[ -d "$BASE/n1" ] && { echo "ERROR: $BASE/n1 exists - run ./99_cleanup.sh first"; exit 1; }
mkdir -p "$RESULTS"
./start_node.sh 1; ./start_node.sh 2; ./start_node.sh 3
"$BIN" init --insecure --host=127.0.0.1:$(sqlport 1)
for n in 1 2 3; do ./wait_sql.sh $n; done
csql -e "
CREATE DATABASE raftlab;
CREATE TABLE raftlab.t (seq INT8 PRIMARY KEY, ts TIMESTAMPTZ NOT NULL DEFAULT now());
ALTER TABLE raftlab.t CONFIGURE ZONE USING num_replicas = 3, constraints = '[]', lease_preferences = '[[+zone=z3]]';"
{ "$BIN" version | head -1; "$BIN" node status --insecure --host=127.0.0.1:$(sqlport 1) --format=csv; } | tee "$RESULTS/cluster.txt"
echo "OK: 3-node cluster up. DB Console: http://127.0.0.1:$(httpport 1)"
start_node.sh: start or restart one node
#!/bin/bash
# start_node.sh <n> : start (or restart) node n in the background
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
n=$1
ulimit -n 65536 2>/dev/null || true
JOIN=127.0.0.1:$(sqlport 1),127.0.0.1:$(sqlport 2),127.0.0.1:$(sqlport 3)
nohup "$BIN" start --insecure --store="$BASE/n$n" \
  --listen-addr=127.0.0.1:$(sqlport $n) --http-addr=127.0.0.1:$(httpport $n) \
  --join="$JOIN" --locality=zone=z$n --cache=1GiB --max-sql-memory=1GiB \
  >> "$BASE/n$n.out" 2>&1 &
echo $! > "$BASE/n$n.pid"
writer.sh: one session, every commit timestamped
#!/bin/bash
# writer.sh <prefix> : one session on node 1, one INSERT per transaction, every commit ack timestamped
# stops cleanly when <prefix>.stop exists
cd "$(dirname "$0")"; source ./00_env.sh
i=0
while [ ! -f "$1.stop" ]; do i=$((i + 1)); echo "INSERT INTO t (seq) VALUES ($i) RETURNING seq;"; done \
  | stdbuf -oL "$PSQL" "host=127.0.0.1 port=$(sqlport 1) user=root dbname=raftlab sslmode=disable connect_timeout=5" \
      -Atq -v ON_ERROR_STOP=0 2> "$1.err" \
  | stamp > "$1.acks"
03_failover_run.sh: kill the leaseholder, restart it, measure
#!/bin/bash
# 03_failover_run.sh <k> : writes on node 1, kill -9 the leaseholder (node 3), restart it, measure
set -uo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
k=$1; P=$RESULTS/run$k
csql -e "TRUNCATE raftlab.t" >/dev/null
# make sure node 3 holds the lease before we start
for i in $(seq 1 60); do
  [ "$(./lease.sh)" = "3" ] && break
  rid=$(csql --format=csv -e "SELECT range_id FROM [SHOW RANGES FROM TABLE raftlab.t]" | tail -n +2 | head -1)
  csql -e "ALTER RANGE $rid RELOCATE LEASE TO 3" >/dev/null 2>&1 || true
  sleep 2
done
[ "$(./lease.sh)" = "3" ] || { echo "ERROR: could not place the lease on node 3"; exit 1; }

rm -f "$P.stop"; ./writer.sh "$P" & WPID=$!
sleep "$WARMUP"
T_KILL=$(now); kill -9 "$(cat "$BASE/n3.pid")"
echo "run $k: node 3 killed at $T_KILL"
sleep 8; LH_AFTER=$(./lease.sh)
sleep $((DOWN - 8))
T_RESTART=$(now); ./start_node.sh 3; NODE=3 ./wait_sql.sh 3
T_BACK=""
for i in $(seq 1 300); do [ "$(./lease.sh)" = "3" ] && { T_BACK=$(now); break; }; sleep 1; done
sleep 10
touch "$P.stop"; wait "$WPID" 2>/dev/null
csql --format=csv -e "SELECT seq FROM raftlab.t" | tail -n +2 > "$P.rows"
printf 't_kill=%s\nt_restart=%s\nt_lease_back=%s\nlease_after_kill=%s\n' \
  "$T_KILL" "$T_RESTART" "${T_BACK:-none}" "$LH_AFTER" > "$P.events"
echo "run $k: done (lease moved to node $LH_AFTER, back on node 3: ${T_BACK:+yes})"
04_summary.sh: pauses, lost commits
#!/bin/bash
# 04_summary.sh : per run - commits acknowledged, commits lost, longest write pause after the kill and after the restart
cd "$(dirname "$0")"; source ./00_env.sh
{
printf '%-4s %9s %6s %7s %14s %16s %16s %12s %14s\n' run acked lost errors writes_per_s pause_kill_s pause_start_s lease_to pause_restart_s
for ev in "$RESULTS"/run*.events; do
  P=${ev%.events}; k=${P##*run}; source "$ev"
  acked=$(wc -l < "$P.acks")
  lost=$(comm -23 <(cut -d, -f1 "$P.acks" | sort) <(sort "$P.rows") | wc -l)
  errs=$(grep -c ERROR "$P.err" 2>/dev/null); errs=${errs:-0}
  read -r g gs g2 tps < <(awk -F, -v k="$t_kill" -v r="$t_restart" '
    NR == 1 { t0 = $2 }
    NR > 1  { d = $2 - p
              if ($2 > k && p < r && d > g) { g = d; gs = p - k }
              if ($2 > r && d > g2) g2 = d }
    { if ($2 < k) nb++; p = $2 }
    END { printf "%.3f %.3f %.3f %.0f\n", g, gs, g2, nb / (k - t0) }' "$P.acks")
  printf '%-4s %9s %6s %7s %14s %16s %16s %12s %14s\n' "$k" "$acked" "$lost" "$errs" "$tps" "$g" "$gs" "n$lease_after_kill" "$g2"
done
echo
echo "pause_kill_s    : longest gap between two commit acks once node 3 (the leaseholder) was killed"
echo "pause_start_s   : when that gap started, relative to the kill (negative = last commit just before it)"
echo "pause_restart_s : longest gap after node 3 was restarted (lease moving back)"
echo "lost            : commits acknowledged to the client but missing from the table (should be 0)"
} | tee "$RESULTS/summary.txt"
01_install.sh: download the binary
#!/bin/bash
# 01_install.sh : get the cockroach binary into $BASE/bin (no root needed)
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
mkdir -p "$BASE/bin"
if [ ! -x "$BIN" ]; then
  TGZ=$BASE/cockroach-$CRDB_VERSION.linux-amd64.tgz
  if [ ! -s "$TGZ" ]; then
    curl -fsSL "https://binaries.cockroachdb.com/cockroach-$CRDB_VERSION.linux-amd64.tgz" -o "$TGZ" || {
      echo "ERROR: download failed. Copy cockroach-$CRDB_VERSION.linux-amd64.tgz to $TGZ and run again."; exit 1; }
  fi
  tar xzf "$TGZ" -C "$BASE"
  cp "$BASE/cockroach-$CRDB_VERSION.linux-amd64/cockroach" "$BIN"
fi
"$BIN" version | head -3
"$PSQL" --version
wait_sql.sh: helper
#!/bin/bash
# wait_sql.sh <n> : wait (max 120 s) until node n answers SQL
cd "$(dirname "$0")"; source ./00_env.sh
for i in $(seq 1 120); do
  NODE=$1 csql -e "SELECT 1" >/dev/null 2>&1 && exit 0; sleep 1
done
echo "ERROR: node $1 not answering SQL"; exit 1
lease.sh: which node holds the lease
#!/bin/bash
# lease.sh : node that holds the lease (leader) of the test table's range
cd "$(dirname "$0")"; source ./00_env.sh
csql --format=csv -e "SELECT lease_holder FROM [SHOW RANGES FROM TABLE raftlab.t WITH DETAILS]" 2>/dev/null | tail -n +2 | head -1
run_all.sh: everything in order
#!/bin/bash
# run_all.sh : install, start, RUNS failover runs, summary (about 5 minutes)
set -euo pipefail
cd "$(dirname "$0")"; source ./00_env.sh
./01_install.sh
./02_start_cluster.sh
for k in $(seq 1 "$RUNS"); do ./03_failover_run.sh "$k"; sleep 15; done
./04_summary.sh
99_cleanup.sh: remove the test nodes
#!/bin/bash
# 99_cleanup.sh : stop the 3 test nodes and delete their data (results are kept)
cd "$(dirname "$0")"; source ./00_env.sh
for n in 1 2 3; do [ -f "$BASE/n$n.pid" ] && kill -9 "$(cat "$BASE/n$n.pid")" 2>/dev/null; done
sleep 2
rm -rf "$BASE"/n1 "$BASE"/n2 "$BASE"/n3 "$BASE"/n*.pid "$BASE"/n*.out
echo "OK: test nodes removed (binary kept in $BASE/bin, results in $RESULTS)"

Oracle 26ai (LiveLabs sandbox, about 25 minutes)

Reserve the free LiveLabs workshop "Use Raft Replication with Distributed Database for Resilient Never-Down Apps" and open a terminal on the sandbox host. In my sandbox only the Customers table existed, so I first created the demo's Orders table through the shard catalog. Then: copy the files into ~/raftora, export APP_PASS=<the app_schema password from the lab>, run ./setup.sh, and then the three runs.

cd ~/raftora && export APP_PASS='...'      # the lab's app_schema password; never hard-code it
./setup.sh                                   # compile, connect, rebalance leaders
nohup bash -c 'for k in 1 2 3; do ./run_test.sh $k || exit 1; sleep 20; done; ./analyze.sh' > runs.log 2>&1 &
tail -f runs.log
orders.sql: the Orders table (child of Customers)
-- orders.sql : child table of the demo's CUSTOMERS table (same definition as the demo's app_schema_auto.sql)
-- run through the shard catalog:  sqlplus app_schema@"(DESCRIPTION=...(SERVICE_NAME=GDS$CATALOG.oradbcloud)))" @orders.sql
ALTER SESSION ENABLE SHARD DDL;
CREATE SHARDED TABLE Orders
( OrderId   INTEGER NOT NULL,
  CustId    VARCHAR2(60) NOT NULL,
  OrderDate TIMESTAMP NOT NULL,
  SumTotal  NUMBER(19,4),
  Status    CHAR(4),
  CONSTRAINT pk_orders PRIMARY KEY (CustId, OrderId),
  CONSTRAINT fk_orders_parent FOREIGN KEY (CustId) REFERENCES Customers ON DELETE CASCADE
) PARTITION BY REFERENCE (fk_orders_parent);
RaftWriter.java: the Java writer: sharding key, timestamps, in-doubt tracking
// RaftWriter.java : Oracle twin of the CockroachDB writer.
// One session, routed by sharding key through the shard directors to the RU leader,
// one INSERT + COMMIT per transaction, every commit acknowledgement timestamped.
// On any error: log it (phase insert/commit), reconnect, carry on with the next number.
// A failure in the COMMIT call is "ambiguous": the client cannot know whether it committed.
//
// usage: java RaftWriter run    <outprefix> <custId> <base>   (stops when <outprefix>.stop exists)
//        java RaftWriter verify <outprefix> <custId> <base>   (writes the rows that exist)
//        java RaftWriter clean  <outprefix> <custId> <base>   (deletes earlier test rows)
import java.io.*;
import java.nio.file.*;
import java.sql.*;
import java.time.Instant;
import java.util.Properties;
import oracle.jdbc.pool.OracleDataSource;

public class RaftWriter {
    static final String URL = "jdbc:oracle:thin:@(DESCRIPTION=(CONNECT_TIMEOUT=10)(TRANSPORT_CONNECT_TIMEOUT=3)(RETRY_COUNT=0)"
        + "(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)"
        + "(ADDRESS=(PROTOCOL=TCP)(HOST=oshard-gsm1.example.com)(PORT=1522))"
        + "(ADDRESS=(PROTOCOL=TCP)(HOST=oshard-gsm2.example.com)(PORT=1522)))"
        + "(CONNECT_DATA=(SERVICE_NAME=oltp_rw_svc.sdb_sys_raft.oradbcloud)))";
    static final String USER = System.getenv().getOrDefault("APP_USER", "app_schema");
    static final String PASS = System.getenv("APP_PASS");          // export APP_PASS=... before running (never hard-code it)

    static String cust; static PrintWriter conn;

    static String now() { Instant i = Instant.now(); return String.format("%d.%06d", i.getEpochSecond(), i.getNano() / 1000); }

    static Connection connect() throws SQLException {
        OracleDataSource ds = new OracleDataSource();
        ds.setURL(URL); ds.setUser(USER); ds.setPassword(PASS);
        Properties p = new Properties();
        p.setProperty("oracle.jdbc.ReadTimeout", "30000");   // never hang forever on a dead socket
        ds.setConnectionProperties(p);
        ShardingKey key = ds.createShardingKeyBuilder().subkey(cust, JDBCType.VARCHAR).build();
        Connection c = ds.createConnectionBuilder().shardingKey(key).build();
        c.setAutoCommit(false);
        try (Statement s = c.createStatement();
             ResultSet r = s.executeQuery("SELECT sys_context('USERENV','CON_NAME') FROM dual")) {
            r.next();
            if (conn != null) { conn.println(now() + "," + r.getString(1)); conn.flush(); }
        }
        return c;
    }

    static void close(AutoCloseable a) { try { if (a != null) a.close(); } catch (Exception e) { } }

    static String clean(String m) { return m == null ? "" : m.replace('\n', ' ').replace(',', ';'); }

    public static void main(String[] a) throws Exception {
        String mode = a[0], out = a[1]; cust = a[2]; long base = Long.parseLong(a[3]);
        String sel = "SELECT OrderId FROM Orders WHERE CustId = ? AND Status = 'RAFT' AND OrderId > ? AND OrderId < ?";
        if (mode.equals("verify") || mode.equals("clean")) {
            try (Connection c = connect()) {
                if (mode.equals("clean")) {
                    try (PreparedStatement d = c.prepareStatement("DELETE FROM Orders WHERE CustId = ? AND Status = 'RAFT' AND ROWNUM <= 50000")) {
                        d.setString(1, cust); int t = 0, n;   // Raft limit: max 100,000 changes per transaction (ORA-05109)
                        do { n = d.executeUpdate(); c.commit(); t += n; } while (n > 0);
                        System.out.println("deleted " + t + " old test rows (batches of 50,000)");
                    }
                    c.commit(); return;
                }
                try (PreparedStatement q = c.prepareStatement(sel); PrintWriter w = new PrintWriter(new FileWriter(out + ".rows"))) {
                    q.setString(1, cust); q.setLong(2, base); q.setLong(3, base + 100_000_000L);
                    int n = 0;
                    try (ResultSet r = q.executeQuery()) { while (r.next()) { w.println(r.getLong(1)); n++; } }
                    System.out.println("rows in table: " + n);
                }
            }
            return;
        }
        // run
        Path stop = Paths.get(out + ".stop");
        PrintWriter acks = new PrintWriter(new BufferedWriter(new FileWriter(out + ".acks")));
        PrintWriter err = new PrintWriter(new FileWriter(out + ".err"), true);
        PrintWriter amb = new PrintWriter(new FileWriter(out + ".amb"), true);
        conn = new PrintWriter(new FileWriter(out + ".conn"), true);
        String ins = "INSERT INTO Orders (OrderId, CustId, OrderDate, SumTotal, Status) VALUES (?, ?, SYSTIMESTAMP, 1, 'RAFT')";
        Connection c = connect();
        PreparedStatement ps = c.prepareStatement(ins);
        long seq = base, n = 0;
        while (!Files.exists(stop)) {
            seq++;
            String phase = "insert";
            try {
                ps.setLong(1, seq); ps.setString(2, cust); ps.executeUpdate();
                phase = "commit";
                c.commit();
                acks.println(seq + "," + now());
                if (++n % 1000 == 0) acks.flush();
            } catch (SQLException e) {
                err.println(now() + "," + phase + "," + seq + "," + e.getErrorCode() + "," + clean(e.getMessage()));
                if (phase.equals("commit")) amb.println(seq);
                close(ps); close(c); c = null;
                while (c == null && !Files.exists(stop)) {
                    try { c = connect(); ps = c.prepareStatement(ins); }
                    catch (SQLException e2) {
                        err.println(now() + ",connect," + seq + "," + e2.getErrorCode() + "," + clean(e2.getMessage()));
                        close(c); c = null; Thread.sleep(100);
                    }
                }
            }
        }
        acks.close(); close(ps); close(c);
    }
}
env.sh: settings and helpers
# env.sh : settings for the Oracle Raft leader-failure test (LiveLabs sandbox)
CUST=${CUST:-0000b998-df45-4183-81d3-41ab455201ff}   # an existing demo customer = the sharding key we write to
WARMUP=${WARMUP:-20}; AFTER=${AFTER:-40}; DOWN=${DOWN:-60}; RUNS=${RUNS:-3}
JH=/u01/app/oracle/product/23c/client_1               # client + JDK inside appclient
OH=/opt/oracle/product/26ai/dbhome_1                  # database home inside shard1..3
R=/tmp/raftora                                        # work dir inside appclient
now() { date +%s.%N; }
ac()  { sudo podman exec -e APP_PASS appclient bash -c "$1"; }   # passes APP_PASS from your shell
ru()  { sudo podman exec gsm1 bash -lc "gdsctl status ru -sort" 2>&1; }
# largest log-index gap between replicas of any RU (-1 if a replica is missing or not Ok)
ru_lag() { ru | awk '/^orcl/ { n++; if ($NF != "Ok") bad = 1; r = $2; v = $5
             if (!(r in mn) || v < mn[r]) mn[r] = v; if (v > mx[r]) mx[r] = v }
           END { m = 0; for (r in mx) if (mx[r] - mn[r] > m) m = mx[r] - mn[r]
                 if (bad || n < 18) m = -1; print m }'; }
dbsql() { sudo podman exec -i --user oracle "shard$1" bash -c \
  'export ORACLE_HOME='"$OH"'; export ORACLE_SID=$(grep -E "^ORCL" /etc/oratab | cut -d: -f1); $ORACLE_HOME/bin/sqlplus -s / as sysdba'; }
# java RaftWriter <mode> <prefix> <base>
jw() { ac "cd $R && $JH/jdk/bin/java -cp .:$JH/jdbc/lib/ojdbc11.jar RaftWriter $1 $R/$2 $CUST $3"; }
writer() { jw "$1" "run$2" $((9000000000 + $2 * 100000000)); }
start_writer() { ac "rm -f $R/$1.stop"; sudo podman exec -d -e APP_PASS appclient bash -c \
  "cd $R && $JH/jdk/bin/java -cp .:$JH/jdbc/lib/ojdbc11.jar RaftWriter run $R/$1 $CUST $2 > $R/$1.log 2>&1" > /dev/null; }
stop_writer() { ac "touch $R/$1.stop"; sleep 5; jw verify "$1" "$2"
  for f in acks err amb conn rows log; do ac "cat $R/$1.$f 2>/dev/null" > "results/$1.$f"; done; }
setup.sh: compile, connection test, rebalance
#!/bin/bash
# setup.sh : copy + compile the writer inside appclient, test the connection, start from balanced leaders
cd "$(dirname "$0")"; source ./env.sh; mkdir -p results
[ -n "$APP_PASS" ] || { echo "ERROR: export APP_PASS=<password of the app_schema user> first"; exit 1; }
ac "mkdir -p $R" && sudo podman cp RaftWriter.java appclient:$R/ || exit 1
ac "cd $R && $JH/jdk/bin/javac -cp $JH/jdbc/lib/ojdbc11.jar RaftWriter.java" || { echo "ERROR: compile failed"; exit 1; }
writer clean 0 || { echo "ERROR: cannot connect as app_schema with the sharding key"; exit 1; }
for n in 1 2 3; do echo "shard$n: $(echo 'select version_full from v$instance;' | dbsql $n | tr -s ' \n' ' ')"; done | tee results/versions.txt
{ echo "=== initial"; ru; } > results/setup_status.txt
echo "rebalancing leaders (gdsctl switchover ru -rebalance) ..."
sudo podman exec gsm1 bash -lc "gdsctl switchover ru -rebalance" 2>&1 | tee results/setup_rebalance.log
sleep 20; { echo "=== after rebalance"; ru; } | tee -a results/setup_status.txt
echo "SETUP OK"
run_test.sh: crash under load, catch-up, planned switchover
#!/bin/bash
# run_test.sh <k> : A) crash the RU leader shard under load   B) restart it, time the catch-up (no load)
#                   C) planned leader switchover (rebalance) under load
cd "$(dirname "$0")"; source ./env.sh; mkdir -p results
k=$1; L=results/run$k; BA=$((9000000000 + k * 100000000)); BB=$((BA + 50000000))
writer clean "$k" > /dev/null
{ echo "=== before"; ru; } > $L.status
# A: crash under load
start_writer "run${k}a" "$BA"; sleep "$WARMUP"
LEADER=$(ac "tail -1 $R/run${k}a.conn 2>/dev/null" | cut -d, -f2 | tr -dc '0-9' | cut -c1)
[ -n "$LEADER" ] || { echo "ERROR: writer not connected"; ac "cat $R/run${k}a.log $R/run${k}a.err"; ac "touch $R/run${k}a.stop"; exit 1; }
echo "run $k: writer on shard$LEADER (leader of the customer's RU) - crashing it"
T_KILL=$(now); echo "shutdown abort" | dbsql "$LEADER" > $L.abort.log 2>&1
sleep 10; { echo "=== 10 s after crashing shard$LEADER"; ru; } >> $L.status
sleep $((AFTER - 10)); T_STOP_A=$(now); stop_writer "run${k}a" "$BA"
# B: restart the shard container, time until its replicas have caught up (no load)
sleep $((DOWN > AFTER ? DOWN - AFTER : 0))
T_RESTART=$(now); sudo podman start "shard$LEADER" > $L.startup.log 2>&1
for i in $(seq 1 120); do sudo podman ps --filter "name=^shard$LEADER\$" --format '{{.Status}}' | grep -q healthy && break; sleep 5; done
T_OPEN=$(now); LAG_OPEN=$(ru_lag)
for i in $(seq 1 360); do [ "$(ru_lag)" = "0" ] && break; sleep 5; done
T_SYNCED=$(now); { echo "=== shard$LEADER back and caught up"; ru; } >> $L.status
echo "run $k: shard$LEADER back, caught up $(awk -v a="$T_OPEN" -v b="$T_SYNCED" 'BEGIN{printf "%.0f", b - a}') s after opening (lag at open: $LAG_OPEN)"
# C: planned leader switchover under load
start_writer "run${k}b" "$BB"; sleep 15
T_REB=$(now); sudo podman exec gsm1 bash -lc "gdsctl switchover ru -rebalance" > $L.rebalance.log 2>&1; T_REB_END=$(now)
sleep 15; stop_writer "run${k}b" "$BB"
{ echo "=== after rebalance"; ru; } >> $L.status
printf 'leader=%s\nt_kill=%s\nt_stop_a=%s\nt_restart=%s\nt_open=%s\nlag_open=%s\nt_synced=%s\nt_reb=%s\nt_reb_end=%s\n' \
  "$LEADER" "$T_KILL" "$T_STOP_A" "$T_RESTART" "$T_OPEN" "$LAG_OPEN" "$T_SYNCED" "$T_REB" "$T_REB_END" > $L.events
echo "run $k: done"
analyze.sh: summary
#!/bin/bash
# analyze.sh : per run - crash under load (A), catch-up after restart, planned switchover under load (B)
cd "$(dirname "$0")"; source ./env.sh
gap() { awk -F, -v s="$2" -v e="$3" 'NR > 1 { d = $2 - p; if ($2 > s && p < e && d > g) { g = d; gs = p - s } } { p = $2 }
        END { printf "%.3f %.3f\n", g, gs }' "$1"; }
rate() { awk -F, -v k="$2" 'NR == 1 { t0 = $2 } $2 < k { n++ } END { printf "%.0f", n / (k - t0) }' "$1"; }
lost() { comm -23 <(cut -d, -f1 "$1.acks" | sort) <(sort "$1.rows") | wc -l; }
{
printf '%-4s %-7s | %8s %5s %8s %11s %11s %5s | %9s %8s | %8s %5s %9s %5s\n' run crashed acked_A lost w/s pause_crash pause_start errs lag_open catchup_s acked_B lost pause_reb errs
for ev in results/run*.events; do
  L=${ev%.events}; k=${L##*run}; source "$ev"; A=${L}a; B=${L}b
  read -r g gs < <(gap $A.acks "$t_kill" "$t_stop_a"); read -r g2 x < <(gap $B.acks "$t_reb" "$t_reb_end")
  cu=$(awk -v a="$t_open" -v b="$t_synced" 'BEGIN{printf "%.0f", b - a}')
  printf '%-4s %-7s | %8s %5s %8s %11s %11s %5s | %9s %8s | %8s %5s %9s %5s\n' "$k" "shard$leader" \
    "$(wc -l < $A.acks)" "$(lost $A)" "$(rate $A.acks "$t_kill")" "$g" "$gs" "$(wc -l < $A.err)" \
    "$lag_open" "$cu" "$(wc -l < $B.acks)" "$(lost $B)" "$g2" "$(wc -l < $B.err)"
done
echo
for ev in results/run*.events; do
  L=${ev%.events}; k=${L##*run}; source "$ev"
  for p in a b; do
    F=$L$p; [ "$p" = a ] && t0=$t_kill || t0=$t_reb
    echo "--- run $k$p ($([ $p = a ] && echo 'crash' || echo 'planned switchover')): ambiguous commits and their real outcome"
    while read -r s; do [ -n "$s" ] && echo "  seq $s : $(grep -qx "$s" $F.rows && echo 'COMMITTED (in table)' || echo 'not committed')"; done < $F.amb
    echo "  errors (phase,ORA code):"; cut -d, -f2,4 $F.err | sort | uniq -c | sed 's/^/    /'
    echo "  (re)connections (s relative to the event, PDB):"; awk -F, -v k="$t0" '{printf "    %+8.3f  %s\n", $1 - k, $2}' $F.conn
  done
done
echo
echo "pause_crash : longest gap between two commit acks after the leader shard was crashed (writer A)"
echo "pause_start : when that gap started, relative to the crash command"
echo "lag_open    : log entries the restarted shard was behind when its container was healthy again"
echo "catchup_s   : seconds from healthy until every replica had the same log index (no load)"
echo "pause_reb   : longest gap during gdsctl switchover ru -rebalance, under load (writer B)"
echo "lost        : commits acknowledged to the client but missing from the table (should be 0)"
} | tee results/summary.txt

Command cheat sheet

The commands I used most, for your own lab:

Oracle 26ai: Globally Distributed Database with Raft replication

-- which shard leads / follows each replication unit (compare the Log Index column!)
gdsctl status ru -sort

-- the topology: shards, chunks, services
gdsctl config sdb
gdsctl config shard
gdsctl config chunks

-- spread the leaders evenly again (e.g. after a shard came back)
gdsctl switchover ru -rebalance

-- DDL sent from the catalog to the shards, and its status
gdsctl show ddl

-- create a sharded child table: connect to the catalog (GDS$CATALOG service) first
ALTER SESSION ENABLE SHARD DDL;
CREATE SHARDED TABLE orders ( ...,
  CONSTRAINT fk_orders_parent FOREIGN KEY (custid) REFERENCES customers )
  PARTITION BY REFERENCE (fk_orders_parent);

CockroachDB

-- where is the lease (leader) of a table's range?
SHOW RANGES FROM TABLE t WITH DETAILS;

-- keep 3 replicas and prefer the lease in zone z3 (constraints must be set too)
ALTER TABLE t CONFIGURE ZONE USING
  num_replicas = 3, constraints = '[]', lease_preferences = '[[+zone=z3]]';

-- move a range's lease by hand
ALTER RANGE <range_id> RELOCATE LEASE TO <store_id>;

-- node list with locality and liveness (instead of crdb_internal in v26.2)
cockroach node status --host=<node>:26257 --certs-dir=<certs>   # --insecure only in a local test lab

Summary

Oracle 26ai and CockroachDB both deliver what Raft promises: in six crashes of the node holding the leader, not one acknowledged commit was lost. The differences are in the architecture around Raft. Oracle routes sessions by sharding key through shard directors and failed over in under a second in my sandbox, but leaves leader placement to the DBA. CockroachDB needs no router and no data-placement design and rebalances itself, but paused writes for about four seconds with default settings. And on both, one transaction per crash ended in doubt, and sometimes it had committed. Design your application for that moment, whichever database you choose.

For a related Oracle 26ai test, see Concurrent refresh of on-commit materialized views in Oracle 26ai.

References

Tested by me: Oracle AI Database 26ai (23.26.3.0.0) in an Oracle LiveLabs sandbox, and CockroachDB v26.2.0 on a dedicated RHEL 8 test server (16 vCPUs, 62 GB RAM). All data is synthetic, three runs per database, default settings; results will vary with hardware, network and workload. Test in a non-production environment.

Tamilselvan Perumal is an Oracle ACE Associate and Senior DBA with 12+ years in banking databases, working on database performance and benchmarking. Connect on LinkedIn.