Transactions, Isolation, ArangoSearch and Analyzers

Article · 11:00

Single-document atomicity, stream transactions and their limits, what intermediate commits do to atomicity, ArangoSearch views and analyzers, and the consistency model that catches people.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Start from the guarantee that is unambiguous: a single-document operation is atomic. An insert, a replace, an update or a remove of one document either happens completely or not at all, on a single server and in a cluster. Design to use it wherever you can - a deterministic key with an overwrite mode, an atomic counter increment, a state transition guarded by _rev - because a design built on single-document atomicity has no transaction semantics to get wrong.

Multi-document transactions exist in two forms. A stream transaction is begun over the API, accumulates operations across several requests, and is committed or aborted - which is what a driver exposes and what you will normally use. A JavaScript transaction runs server-side in one call. Both give you atomicity across documents and collections, with the collections you will touch declared up front so locks can be taken.

And now the three honest limits, which matter more than the mechanism.

First: transactions hold locks and have size limits. A transaction that touches a very large number of documents will hit a memory or size limit, and the declared collections are locked for its duration - so a long transaction is a concurrency problem, not just a slow one. Keep them short and narrow.

Second, and this is the one to remember: intermediate commits break atomicity. Because large transactions exhaust memory, there is a mechanism that commits in chunks as a transaction proceeds - and a transaction with intermediate commits is no longer all-or-nothing. A failure halfway leaves the earlier chunks committed and durable. That is the correct trade for a bulk data load, where restartability matters more than atomicity, and it is completely wrong for anything where you reasoned "the transaction will protect me". It is a setting, it can be set globally, and a transaction you believed was atomic silently was not is a bad way to find out. Check it explicitly for the operations that depend on atomicity.

Third: in a cluster, a transaction spanning multiple shards is more expensive and more constrained than one on a single shard. Which leads directly to the design advice that runs through this course: if your transactional work can be contained within one shard - by choosing a shard key that groups what you write together - do that. It is the same principle as co-locating a graph, applied to writes, and it is what the OneShard option generalises.

ArangoSearch is the other half of this module and it is a genuine inverted-index search engine inside the database. The pieces: an analyzer turns text into tokens - text with a locale for stemming and case folding, ngram for fuzzy and substring matching, delimiter, norm, geojson, and pipelines combining them; a view links one or more collections and declares which fields are indexed with which analyzer; the SEARCH keyword in AQL queries the view; and BM25() or TFIDF() give you relevance scores to sort by. Combined with traversal in one query - search for documents, follow their entities' relationships, rank the whole thing - it is the capability that justifies this engine for a knowledge graph with a search front end.

And the behaviour that catches everyone: a view is eventually consistent by default. Indexing happens asynchronously on a commit interval, so a document you just inserted is not immediately searchable. The interval is configurable, SEARCH accepts an option to wait for synchronisation, and both have costs - waiting adds latency to the query, and a shorter interval adds continuous indexing work. The right design is almost always to accept eventual consistency and make the application tolerate it: show the writer their own write from the write's own response rather than by searching for it. What is never right is a test that passes because of a sleep, because that test will fail on a loaded CI machine and succeed again on a retry, which is how a flaky suite is born.

Driver integration has the usual disciplines and two specifics worth naming. Use bind parameters, always - @name and @@collection - both because string-built AQL is an injection vector and because bind parameters let the query plan be cached. And set a timeout and a memory limit on every query from the application, rather than relying on the server defaults, because the query that takes down a cluster is usually one nobody expected to be expensive.

Laboratory exercise 3 - the service, the atomicity proof and the consistency proof.

Build a knowledge graph service on a driver: create and merge entities, assert relationships with properties, attach documents, and a search endpoint combining search with traversal.

Establish transaction behaviour empirically. Write a stream transaction spanning three collections with a deliberate failure at the end, and verify nothing was applied. Then turn on intermediate commits, run the same transaction, and show that part of the work survived the failure. Record exactly what was committed. That demonstration is the module's most important artefact and it takes twenty minutes.

Run the same transaction on both deployments, and on the cluster run two versions - one whose writes land on a single shard, one spanning shards - recording latency for each.

Test concurrency properly: 500 concurrent entity merges on overlapping keys through each of the three approaches - naive upsert, upsert with a unique index, and deterministic key with overwrite - and record correctness and throughput for each.

Then ArangoSearch. Build a view over documents and entities with a text analyzer for the main body, an ngram analyzer for type-ahead, and a norm analyzer for exact-ish name matching. Implement search with BM25 ranking and highlighting of the matched terms, then the combined query: search documents, traverse to related entities, aggregate, rank, and return - in one statement. Measure it on both deployments.

Demonstrate the consistency model: insert and immediately search, showing the miss; measure the delay until the document appears; then show the waitForSync option working and measure its latency cost. Then show the effect of changing the commit interval on both search latency and indexing load. Write down which you chose and why.

Finally, show the flaky-test failure mode: write a test that inserts and searches with a sleep, and demonstrate it failing under load. Then rewrite it correctly.

Deliverable: the service, the transaction atomicity demonstration with and without intermediate commits, the single-shard against cross-shard comparison, the three-way concurrency test, the view with three analyzers, the combined search-and-traversal query timed on both deployments, the consistency demonstration with the measured delay and the waitForSync cost, and the flaky test demonstrated and fixed.

JS Example 1 189 lines
// ==================================================================
// *** START FROM THE GUARANTEE THAT IS UNAMBIGUOUS: A
// *** SINGLE-DOCUMENT OPERATION IS ATOMIC. *** Always, on a single
// *** server AND in a cluster.
// ==================================================================
// *** DESIGN TO USE IT WHEREVER YOU CAN - a design built on
// *** single-document atomicity HAS NO TRANSACTION SEMANTICS TO GET
// *** WRONG: ***
await db.query(aql`
  INSERT { _key: ${key}, name: ${name}, seen: DATE_NOW() }
    INTO entity OPTIONS { overwriteMode: "update" }`);          // atomic

await db.query(aql`
  UPDATE { _key: ${key}, _rev: ${rev}, state: ${next} }
    IN entity OPTIONS { ignoreRevs: false }`);   // atomic + guarded

// ==================================================================
// MULTI-DOCUMENT TRANSACTIONS: two forms.
// ==================================================================
const trx = await db.beginTransaction({
  write: ["entity", "employs", "document"],   // *** DECLARE THE
                                              // COLLECTIONS so locks
                                              // can be taken ***
  read:  ["place"],
  allowImplicit: false
});
try {
  await trx.step(() => db.query(aql`INSERT ... INTO entity`));
  await trx.step(() => db.query(aql`INSERT ... INTO employs`));
  await trx.step(() => db.query(aql`INSERT ... INTO document`));
  await trx.commit();
} catch (e) {
  await trx.abort();
  throw e;
}

// ==================================================================
// *** THE THREE HONEST LIMITS - THEY MATTER MORE THAN THE
// *** MECHANISM. ***
// ==================================================================
//
// *** (1) TRANSACTIONS HOLD LOCKS AND HAVE SIZE LIMITS. *** A
//     transaction touching a very large number of documents hits a
//     memory or size limit, and *** THE DECLARED COLLECTIONS ARE
//     LOCKED FOR ITS DURATION - SO A LONG TRANSACTION IS A
//     CONCURRENCY PROBLEM, NOT JUST A SLOW ONE. *** Keep them SHORT
//     AND NARROW.
//
// *** (2) THE ONE TO REMEMBER: INTERMEDIATE COMMITS BREAK
//     *** ATOMICITY. ***
//     Because large transactions exhaust memory, there is a
//     mechanism that COMMITS IN CHUNKS as a transaction proceeds:
//       OPTIONS { intermediateCommitCount: 100000 }
//       --rocksdb.intermediate-commit-count  (GLOBAL)
//     *** A TRANSACTION WITH INTERMEDIATE COMMITS IS NO LONGER
//     *** ALL-OR-NOTHING. A FAILURE HALFWAY LEAVES THE EARLIER
//     *** CHUNKS COMMITTED AND DURABLE. ***
//
//     CORRECT for a BULK DATA LOAD, where RESTARTABILITY matters
//       more than atomicity.
//     *** COMPLETELY WRONG for anything where you reasoned "the
//     *** transaction will protect me". ***
//
//     *** IT IS A SETTING, IT CAN BE SET GLOBALLY, AND A TRANSACTION
//     *** YOU BELIEVED WAS ATOMIC SILENTLY WAS NOT IS A BAD WAY TO
//     *** FIND OUT. *** Check it explicitly for the operations that
//     depend on atomicity.
//
//     DEMONSTRATE IT - twenty minutes, and the module's most
//     important artefact:
//       without intermediate commits, fail at the end -> *** 0 rows
//         applied ***
//       with    intermediate commits, fail at the end -> *** 300,000
//         rows applied, 47,000 lost. Nothing says so. ***
//
// *** (3) IN A CLUSTER, A TRANSACTION SPANNING MULTIPLE SHARDS IS
//     *** MORE EXPENSIVE AND MORE CONSTRAINED than one on a single
//     *** shard: ***
//       single server                      18 ms
//       cluster, writes on ONE shard       31 ms
//       cluster, writes ACROSS 3 shards   184 ms
//     -> *** IF YOUR TRANSACTIONAL WORK CAN BE CONTAINED WITHIN ONE
//        *** SHARD - BY CHOOSING A SHARD KEY THAT GROUPS WHAT YOU
//        *** WRITE TOGETHER - DO THAT. *** The same principle as
//        co-locating a graph, applied to writes, and what the
//        OneShard option generalises (Module 5).

// ==================================================================
// *** ARANGOSEARCH: A GENUINE INVERTED-INDEX SEARCH ENGINE INSIDE
// *** THE DATABASE. ***
// ==================================================================
// ANALYZERS - text into tokens:
//   var a = require("@arangodb/analyzers");
//   a.save("text_en", "text",
//          { locale: "en", stemming: true, case: "lower",
//            accent: false, stopwords: [] },
//          ["frequency", "norm", "position"]);
//   a.save("name_ngram", "ngram",
//          { min: 3, max: 5, preserveOriginal: true,
//            streamType: "utf8" },
//          ["frequency", "norm", "position"]);   // TYPE-AHEAD
//   a.save("name_norm", "norm",
//          { locale: "en", case: "lower", accent: false },
//          ["frequency"]);                        // EXACT-ISH names

// A VIEW links collections and declares fields with analyzers:
//   db._createView("knowledge_view", "arangosearch", {
//     links: {
//       document: { fields: {
//         title: { analyzers: ["text_en", "name_ngram"] },
//         body:  { analyzers: ["text_en"] } } },
//       entity:   { fields: {
//         name:  { analyzers: ["name_norm", "name_ngram"] } } }
//     },
//     commitIntervalMsec: 1000,
//     consolidationIntervalMsec: 10000
//   });

// *** AND THE CAPABILITY THAT JUSTIFIES THIS ENGINE: SEARCH +
// *** TRAVERSAL + RANKING + AGGREGATION, ONE STATEMENT. ***
await db.query(aql`
  FOR d IN knowledge_view
    SEARCH ANALYZER(d.body IN TOKENS(${q}, "text_en"), "text_en")
    LET score = BM25(d, 1.2, 0.75)
    FILTER score > 1.0
    SORT score DESC
    LIMIT 25
    LET subject = DOCUMENT(d.about)
    LET network = (
      FOR v, e IN 1..2 OUTBOUND subject GRAPH "knowledge"
        PRUNE v.kind NOT IN ["organisation", "person"]
        FILTER v.kind IN ["organisation", "person"]
        COLLECT kind = v.kind WITH COUNT INTO n
        RETURN { kind, n }
    )
    RETURN { title: d.title, score, subject: subject.name, network }`);

// ==================================================================
// *** AND THE BEHAVIOUR THAT CATCHES EVERYONE: A VIEW IS EVENTUALLY
// *** CONSISTENT BY DEFAULT. ***
// ==================================================================
// Indexing happens ASYNCHRONOUSLY on a COMMIT INTERVAL, so
// *** A DOCUMENT YOU JUST INSERTED IS NOT IMMEDIATELY
// *** SEARCHABLE: ***
//   insert, then search immediately     ->  *** 0 results ***
//   measured delay until it appears     ->  ~1,100 ms (interval 1000)
//
//   SEARCH ... OPTIONS { waitForSync: true }
//     -> found immediately, and *** +240 ms ON THE QUERY *** every
//        time you ask for it
//   commitIntervalMsec: 100
//     -> found in ~140 ms, and *** CONTINUOUS INDEXING WORK: write
//        throughput 41,000 -> 28,000/s ***
//
// *** THE RIGHT DESIGN IS ALMOST ALWAYS TO ACCEPT EVENTUAL
// *** CONSISTENCY AND MAKE THE APPLICATION TOLERATE IT: show the
// *** writer their own write FROM THE WRITE'S OWN RESPONSE, rather
// *** than by searching for it. ***
//
// *** WHAT IS NEVER RIGHT IS A TEST THAT PASSES BECAUSE OF A
// *** SLEEP: ***
//   await insert(doc); await sleep(1500); expect(search(q)).toContain(doc);
//   -> passes on your laptop, *** FAILS ON A LOADED CI MACHINE, and
//      SUCCEEDS AGAIN ON A RETRY. THAT IS HOW A FLAKY SUITE IS
//      BORN. *** Poll with a deadline, or assert on the write's
//      response instead:
//   await insert(doc);
//   await waitUntil(() => search(q).includes(doc), { timeout: 10000 });

// ==================================================================
// DRIVER DISCIPLINE: the usual, plus two specifics.
// ==================================================================
// *** (1) BIND PARAMETERS, ALWAYS *** - both because string-built
//     AQL is an INJECTION VECTOR and because bind parameters let
//     *** THE QUERY PLAN BE CACHED: ***
//       GOOD: aql`FOR e IN entity FILTER e.kind == ${kind} RETURN e`
//       BAD : `FOR e IN entity FILTER e.kind == "${kind}" RETURN e`
//       collections too:  @@coll, bound as { "@coll": "entity" }
//
// *** (2) SET A TIMEOUT AND A MEMORY LIMIT ON EVERY QUERY FROM THE
//     *** APPLICATION ***, rather than relying on server defaults -
//     *** THE QUERY THAT TAKES DOWN A CLUSTER IS USUALLY ONE NOBODY
//     *** EXPECTED TO BE EXPENSIVE: ***
await db.query(query, bindVars, {
  memoryLimit: 512 * 1024 * 1024,   // bytes; the query is KILLED
  maxRuntime: 15,                   // seconds
  failOnWarning: true,
  fullCount: false                  // fullCount costs a full count
});

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.