<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Database Best Practices - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/database-best-practices/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Thu, 26 Nov 2026 18:01:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Database Best Practices - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>SQLite Best Practices for Production: WAL, PRAGMA, Backups</title>
		<link>https://thecodebuzz.com/sqlite-best-practices-production/</link>
					<comments>https://thecodebuzz.com/sqlite-best-practices-production/#respond</comments>
		
		<dc:creator><![CDATA[Izzy]]></dc:creator>
		<pubDate>Wed, 18 Nov 2026 23:39:57 +0000</pubDate>
				<category><![CDATA[Database Best Practices]]></category>
		<category><![CDATA[PRAGMA Settings]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[SQLite Production]]></category>
		<category><![CDATA[WAL Mode]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=31054</guid>

					<description><![CDATA[<p>SQLite best practices for production: when it fits, WAL mode and PRAGMA settings, fixing 'database is locked', safe backups and when to move to PostgreSQL.</p>
<p>The post <a href="https://thecodebuzz.com/sqlite-best-practices-production/">SQLite Best Practices for Production: WAL, PRAGMA, Backups</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Today we will see how to run SQLite safely in production, which settings to apply and where it stops being the right choice. SQLite is an embedded, serverless SQL engine that reads and writes a single file inside your application process. This guide is for engineers, architects and DBAs who want to follow SQLite best practices production teams can rely on, without guessing.</p>
<p>We will cover a fit check, WAL mode and PRAGMA settings, schema design, concurrency and connection handling, backups, security and upgrades. Each section explains the reason behind the rule, so you can decide when a rule does not apply to your case.</p>
<p>Before we start, check the version. The latest release is SQLite 3.54.1, dated 2026-10-16, a patch release that fixes a few problems in 3.54.0 (2026-10-09). SQLite follows a latest-version model, so there is no LTS line and no fixed end-of-life date. STRICT tables need SQLite 3.37 or later. The examples use the <code>sqlite3</code> shell, C# (Microsoft.Data.Sqlite) and Python.</p>
<blockquote><p><strong>Version note:</strong> This guide targets SQLite 3.54.1 (released 2026-10-16), with notes on the 3.53 line (latest 3.53.4) and a 3.37 minimum for STRICT tables.</p>
<p>&nbsp;</p>
<p><strong>In this guide</strong></p></blockquote>
<p>&nbsp;</p>
<ul>
<li><a href="#sqlite-best-practices-for-production-at-a-glance">SQLite Best Practices for Production at a Glance</a></li>
<li><a href="#sqlite-wal-mode-and-pragma-settings-for-production">SQLite WAL Mode and PRAGMA Settings for Production</a></li>
<li><a href="#schema-design-indexing-and-query-optimization">Schema Design, Indexing and Query Optimization</a></li>
<li><a href="#fix-sqlite-x27-database-is-locked-x27-errors-concurrency-and">Fix SQLite &#8216;database is locked&#8217; Errors: Concurrency and Connection Pooling</a></li>
<li><a href="#backups-replication-security-containers-and-upgrades">Backups, Replication, Security, Containers and Upgrades</a></li>
<li><a href="#common-anti-patterns-and-production-readiness-checklist">Common Anti-Patterns and Production Readiness Checklist</a></li>
<li><a href="#key-takeaways">Key takeaways</a></li>
<li><a href="#faq">FAQ</a></li>
</ul>
<p>&nbsp;</p>
<h2 id="sqlite-best-practices-for-production-at-a-glance">SQLite Best Practices for Production at a Glance</h2>
<p>&nbsp;</p>
<p>Yes, SQLite is production-ready when the application and the database file live on the same machine and your write volume fits a single-writer model. A <strong>single-writer model</strong> means only one write transaction runs at a time, while any number of readers can run alongside it. If your writes can be batched and queued through one connection, SQLite in production works well.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note: </strong> SQLite is a library that opens one file inside your own process, not a server you connect to. Think of a notebook you carry with you versus a records office you phone. The notebook is instant and needs no staff, but only the person holding it can write in it. The analogy stops fitting in one place: several readers can look at the same SQLite file at once.</p></blockquote>
<h3>Which SQLite Production Practices Matter Most?</h3>
<p>The table below lists the rules this guide covers, with the practice to follow and the mistake to avoid for each area.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Area</th>
<th>Do this</th>
<th>Avoid this</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Fit</strong></td>
<td>Use it for same-machine access with a serialized writer</td>
<td>Many networked clients writing to one file</td>
</tr>
<tr>
<td><strong>Journal mode</strong></td>
<td>Enable WAL (write-ahead log) mode</td>
<td>Default rollback journal under mixed read/write load</td>
</tr>
<tr>
<td><strong>Per-connection PRAGMAs</strong></td>
<td>Set synchronous, busy_timeout, foreign_keys and cache_size on every connection</td>
<td>Assuming settings carry over from other connections</td>
</tr>
<tr>
<td><strong>Schema types</strong></td>
<td>Use STRICT tables</td>
<td>Relying on type affinity to reject bad values</td>
</tr>
<tr>
<td><strong>Transactions</strong></td>
<td>Use BEGIN IMMEDIATE for writes and batch inserts</td>
<td>One commit per row, or deferred transactions that write</td>
</tr>
<tr>
<td><strong>Connections</strong></td>
<td>One writer plus several readers</td>
<td>Many connections competing to write</td>
</tr>
<tr>
<td><strong>Backups</strong></td>
<td>Use .backup or VACUUM INTO, then test restores</td>
<td>Copying only the .db file</td>
</tr>
<tr>
<td><strong>Storage</strong></td>
<td>Local disk or a single-attached block volume</td>
<td>NFS or CIFS network shares</td>
</tr>
<tr>
<td><strong>Upgrades</strong></td>
<td>Track patch releases and check the driver&#8217;s bundled version</td>
<td>Pinning an old version forever</td>
</tr>
<tr>
<td><strong>Security</strong></td>
<td>Restrict file permissions, encrypt, use bound parameters</td>
<td>World-readable files and string-built SQL</td>
</tr>
</tbody>
</table>
</figure>
<h3>When Should You Use SQLite?</h3>
<p>Use SQLite when simple administration and maintenance matter more than enterprise features. The official guidance names embedded and IoT devices, local data files, data analysis and caches of enterprise data as good fits.</p>
<p>Choose a client/server database when many client programs send SQL to the same database over a network. SQLite still works when the application server and the file sit on the same machine, even if end users are another network hop away. The animated diagram below walks a new workload through three questions to reach a decision.</p>
<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/sqlite-best-practices-production-diagram-1.gif" alt="Decision tree: three questions on networked writers, local disk and a single serialized writer lead to SQLite with WAL or PostgreSQL/MySQL." width="1200" height="675" /><figcaption>Any failing answer routes to a client/server database; passing all three questions makes SQLite with WAL a good fit.</figcaption></figure>
<h3>SQLite vs PostgreSQL vs MySQL</h3>
<p>This table compares the three engines on the points that most often decide the choice.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Concern</th>
<th>SQLite</th>
<th>PostgreSQL</th>
<th>MySQL</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Process model</strong></td>
<td>Library inside your process</td>
<td>Separate server</td>
<td>Separate server</td>
</tr>
<tr>
<td><strong>Concurrent writers</strong></td>
<td>One at a time</td>
<td>Many</td>
<td>Many</td>
</tr>
<tr>
<td><strong>Network access</strong></td>
<td>None built in</td>
<td>Built in</td>
<td>Built in</td>
</tr>
<tr>
<td><strong>Administration</strong></td>
<td>Minimal, one file</td>
<td>Users, tuning, upgrades</td>
<td>Users, tuning, upgrades</td>
</tr>
<tr>
<td><strong>Replication</strong></td>
<td>None built in; use backup streaming tools</td>
<td>Built-in streaming replication</td>
<td>Built-in replication</td>
</tr>
<tr>
<td><strong>Typing</strong></td>
<td>Flexible affinity; STRICT is opt-in</td>
<td>Strictly typed columns</td>
<td>Typed columns, enforcement set by SQL mode</td>
</tr>
</tbody>
</table>
</figure>
<h3>When Should You Move from SQLite to PostgreSQL?</h3>
<p>Move when one of these triggers appears, and not before. Each one means the single-writer, same-machine model no longer holds.</p>
<ul>
<li><strong>Shared data:</strong> several app servers need the same data at the same time.</li>
<li><strong>Write queueing:</strong> writes keep queueing even after batching and short transactions.</li>
<li><strong>Missing features:</strong> your workload needs features SQLite does not offer.</li>
<li><strong>Replication and roles:</strong> you need built-in streaming replication or fine-grained roles.</li>
<li><strong>Network storage:</strong> the file must live on network storage you cannot avoid.</li>
</ul>
<h2 id="sqlite-wal-mode-and-pragma-settings-for-production">SQLite WAL Mode and PRAGMA Settings for Production</h2>
<p>For SQLite in production, enable WAL, set <code>synchronous=NORMAL</code>, <code>busy_timeout</code>, <code>foreign_keys=ON</code> and a larger cache on every connection. <strong>WAL (write-ahead log)</strong> is a journal mode where changes are appended to a separate <code>-wal</code> file instead of overwriting pages in the main database file.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note: </strong> Think of a shop ledger with a separate logbook beside it. New entries go into the logbook first and are merged into the main ledger later. Readers keep reading the old ledger pages while one writer adds to the logbook. The analogy stops at one point: SQLite still allows only one writer at a time.</p></blockquote>
<h3>Which SQLite PRAGMA settings should you use?</h3>
<p>The table below shows each setting, where it is stored, a common production value and the reason. Only <code>journal_mode</code> survives in the file, so the rest belong in your connection factory.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Setting</th>
<th>Persistence</th>
<th>Recommended value</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>journal_mode</strong></td>
<td>Stored in the database file</td>
<td><code>WAL</code></td>
<td>Readers don&#8217;t block the writer, and the writer doesn&#8217;t block readers.</td>
</tr>
<tr>
<td><strong>synchronous</strong></td>
<td>Per connection</td>
<td><code>NORMAL</code></td>
<td>Fewer disk syncs in WAL. A power loss can drop the latest commits, but the file stays consistent.</td>
</tr>
<tr>
<td><strong>busy_timeout</strong></td>
<td>Per connection</td>
<td><code>5000</code> (ms)</td>
<td>Waits for a lock instead of failing at once with SQLITE_BUSY.</td>
</tr>
<tr>
<td><strong>foreign_keys</strong></td>
<td>Per connection</td>
<td><code>ON</code></td>
<td>Enforcement is off by default, so constraints are ignored without it.</td>
</tr>
<tr>
<td><strong>cache_size</strong></td>
<td>Per connection</td>
<td><code>-64000</code></td>
<td>A negative number means KB, so this is about 64 MB of page cache.</td>
</tr>
</tbody>
</table>
</figure>
<p>Run this block in the sqlite3 shell, or issue the same statements from your driver on every new connection:</p>
<p class="code-label"><strong>SQL</strong></p>
<pre><code class="language-sql">-- Persistent: stored in the database file
PRAGMA journal_mode = WAL;

-- Per connection: repeat on every open
PRAGMA synchronous = NORMAL;   -- fewer fsyncs than FULL, safe with WAL
PRAGMA busy_timeout = 5000;    -- wait up to 5 seconds for a lock
PRAGMA foreign_keys = ON;      -- off by default
PRAGMA cache_size = -64000;    -- negative value = KB (about 64 MB)
</code></pre>
<p>Setting <code>journal_mode</code> needs a lock, so it can fail with <strong>&#8220;database is locked&#8221;</strong> when the file is busy. Run it once at startup or in a migration step, not on every request.</p>
<h3>What are the WAL mode limits you must know?</h3>
<ul>
<li><strong>One writer, many readers:</strong> a second writer waits until the first commits or rolls back.</li>
<li><strong>Library version:</strong> SQLite before 3.7.0 can&#8217;t read a WAL database and reports &#8220;file is encrypted or is not a database&#8221;. Every tool and driver that opens the file must be recent enough.</li>
<li><strong>Shared memory file:</strong> WAL uses a <code>-shm</code> file, so keep the database on a local disk.</li>
<li><strong>Exclusive locking mode:</strong> if one connection opens the file in exclusive mode, others can get SQLITE_BUSY. If you set <code>EXCLUSIVE</code> before the first WAL access, no wal-index is created, and the mode stays exclusive until you leave WAL.</li>
</ul>
<h3>How do you stop the WAL file from growing?</h3>
<p>The <code>-wal</code> file grows until a checkpoint copies its content back into the main file. A long-running reader can block that copy (checkpoint starvation), and the WAL keeps growing.</p>
<ol>
<li><strong>Keep read transactions short:</strong> close cursors and transactions as soon as the work is done.</li>
<li><strong>Monitor the file size:</strong> alert when the <code>-wal</code> file keeps growing across several checks.</li>
<li><strong>Force a checkpoint if needed:</strong> run it in a quiet period, as shown below.</li>
</ol>
<p>This statement copies the WAL back and resets the file. It returns three numbers: a busy flag, pages in the log and pages checkpointed.</p>
<p class="code-label"><strong>SQL</strong></p>
<pre><code class="language-sql">PRAGMA wal_checkpoint(TRUNCATE);
</code></pre>
<h2 id="schema-design-indexing-and-query-optimization">Schema Design, Indexing and Query Optimization</h2>
<p>Use <strong>STRICT tables</strong>, an <code>INTEGER PRIMARY KEY</code>, indexes that match your filters, and bound parameters. Without STRICT, SQLite&#8217;s type affinity (its loose rules for converting values to a column&#8217;s declared type) silently accepts a value of the wrong type, such as text in an integer column. STRICT needs SQLite 3.37 or later and is painful to retrofit, so add it when you create the table.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note: </strong> A normal SQLite column is like a form field with a hint label: the hint says &#8220;number&#8221;, but the clerk accepts whatever you write. A STRICT column is a field that rejects the wrong kind of entry at the counter.</p></blockquote>
<h3>How do you define a production-ready table?</h3>
<p>Here is a simplified retail orders table with a foreign key, a CHECK constraint and a composite index:</p>
<p class="code-label"><strong>SQL</strong></p>
<pre><code class="language-sql">CREATE TABLE customers (
  id    INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE
) STRICT;

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  status      TEXT    NOT NULL CHECK (status IN ('new','paid','shipped','cancelled')),
  total_cents INTEGER NOT NULL CHECK (total_cents &gt;= 0),
  created_at  TEXT    NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
) STRICT;

CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at);</code></pre>
<p><code>INTEGER PRIMARY KEY</code> becomes an alias for the internal rowid, so lookups by id go straight to the row. Keep rows narrow and store large blobs elsewhere, because wide rows mean fewer rows per page and more disk reads.</p>
<h3>How do you confirm a query uses an index?</h3>
<p>Run <code>EXPLAIN QUERY PLAN</code> and look for <code>SEARCH</code> instead of <code>SCAN</code>:</p>
<p class="code-label"><strong>SQL</strong></p>
<pre><code class="language-sql">EXPLAIN QUERY PLAN
SELECT id, total_cents FROM orders
WHERE customer_id = ? AND created_at &gt;= ?;
-- Expected: SEARCH orders USING INDEX idx_orders_customer_created (...)</code></pre>
<p>A <code>SCAN</code> on a large table means a full read, so add or reorder an index.</p>
<h3>How do you write safe and fast inserts?</h3>
<p>Pass values as bound parameters (<code>?</code>), never through string formatting. This stops SQL injection and lets SQLite reuse the prepared statement. Batch rows in one transaction, because every commit costs a sync to disk.</p>
<p class="code-label"><strong>Python</strong></p>
<pre><code class="language-python">import sqlite3

conn = sqlite3.connect("shop.db")
conn.execute("PRAGMA foreign_keys = ON")

rows = [(1, "new", 2599), (1, "paid", 1200), (2, "new", 899)]

with conn:  # one transaction, one commit
    conn.executemany(
        "INSERT INTO orders (customer_id, status, total_cents) VALUES (?, ?, ?)",
        rows,
    )</code></pre>
<h3>Which SQLite 3.53 changes affect your schema?</h3>
<ul>
<li><strong>Constraint changes:</strong> <code>ALTER TABLE</code> can add and remove NOT NULL and CHECK constraints, which removes the need for a table rebuild in some migrations.</li>
<li><strong>Expression indexes:</strong> 3.53.0 dealt with stale expression indexes. If you index expressions, upgrade to 3.53.4 or later and run <code>REINDEX EXPRESSIONS</code>.</li>
<li><strong>JSON helpers:</strong> <code>json_array_insert()</code> and <code>jsonb_array_insert()</code> were added.</li>
</ul>
<h2 id="fix-sqlite-x27-database-is-locked-x27-errors-concurrency-and">Fix SQLite &#8216;database is locked&#8217; Errors: Concurrency and Connection Pooling</h2>
<p>The <code>SQLITE_BUSY</code> error (shown as &#8220;database is locked&#8221;) happens because <strong>SQLite runs only one write transaction at a time</strong>, even in WAL mode. To fix it, serialize writes, start write transactions with <code>BEGIN IMMEDIATE</code> and keep them short.</p>
<h3>Why does a deferred transaction fail even with busy_timeout?</h3>
<p>A plain <code>BEGIN</code> is deferred. It starts as a reader and tries to become a writer only when it runs its first write. If another connection has written in between, that upgrade fails with <code>SQLITE_BUSY</code> straight away, and <code>busy_timeout</code> does not help. <code>BEGIN IMMEDIATE</code> takes the write lock at the start, so <code>busy_timeout</code> can wait for it.</p>
<p>The animated diagram below shows both cases, first the failing deferred transaction and then the fixed version.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note: </strong> A deferred transaction is like queueing at a counter to look at a file, then asking to edit it after someone else has taken the only edit slot. <code>BEGIN IMMEDIATE</code> takes a ticket for the edit slot before you start, so you simply wait your turn.</p></blockquote>
<h3>What is the right connection pooling pattern?</h3>
<p>Use one writer connection, or one mutex or write queue in the app, plus several reader connections. In WAL mode readers do not block the writer. Guides suggest moving to PostgreSQL only when this model is outgrown, not before.</p>
<h3>C# example with Microsoft.Data.Sqlite</h3>
<p>This simplified helper applies the PRAGMAs on each connection and runs writes inside an immediate transaction, guarded by a <code>SemaphoreSlim</code>:</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">using Microsoft.Data.Sqlite;

public sealed class SqliteStore
{
    private static readonly SemaphoreSlim WriteGate = new(1, 1);
    private readonly string _cs;

    public SqliteStore(string path) =&gt;
        _cs = new SqliteConnectionStringBuilder { DataSource = path }.ToString();

    public async Task&lt;SqliteConnection&gt; OpenAsync()
    {
        var conn = new SqliteConnection(_cs);
        await conn.OpenAsync();
        using var cmd = conn.CreateCommand();
        cmd.CommandText = @"PRAGMA busy_timeout = 5000;
                            PRAGMA synchronous = NORMAL;
                            PRAGMA foreign_keys = ON;
                            PRAGMA cache_size = -64000;";
        await cmd.ExecuteNonQueryAsync();
        return conn;
    }

    public async Task WriteAsync(Action&lt;SqliteConnection, SqliteTransaction&gt; work)
    {
        await WriteGate.WaitAsync();
        try
        {
            await using var conn = await OpenAsync();
            using var tx = conn.BeginTransaction(deferred: false); // BEGIN IMMEDIATE
            work(conn, tx);
            tx.Commit();
        }
        finally { WriteGate.Release(); }
    }
}</code></pre>
<p>Passing <code>deferred: false</code> makes the provider issue <code>BEGIN IMMEDIATE</code>. Add your own retry logic if needed.</p>
<h3>Python example with sqlite3</h3>
<p>Here <code>isolation_level=None</code> stops the module from opening transactions on its own, so you control <code>BEGIN IMMEDIATE</code> yourself:</p>
<p class="code-label"><strong>Python</strong></p>
<pre><code class="language-python">import sqlite3
from contextlib import contextmanager

def connect(path, readonly=False):
    mode = "ro" if readonly else "rw"
    conn = sqlite3.connect(f"file:{path}?mode={mode}", uri=True,
                           isolation_level=None, timeout=5)
    conn.execute("PRAGMA busy_timeout = 5000")
    conn.execute("PRAGMA foreign_keys = ON")
    conn.execute("PRAGMA synchronous = NORMAL")
    return conn

@contextmanager
def write_tx(conn):
    conn.execute("BEGIN IMMEDIATE")
    try:
        yield conn
        conn.execute("COMMIT")
    except Exception:
        conn.execute("ROLLBACK")
        raise

writer = connect("app.db")
reader = connect("app.db", readonly=True)

with write_tx(writer) as db:
    db.execute("UPDATE orders SET status = ? WHERE id = ?", ("shipped", 42))</code></pre>
<p>The reader opens with <code>mode=ro</code>, so it cannot write by accident.</p>
<h3>Troubleshooting checklist for SQLite database is locked</h3>
<p>Check these causes in order:</p>
<ol>
<li><strong>Long read transactions:</strong> a reader that stays open holds a snapshot and delays checkpoints. Close it quickly.</li>
<li><strong>Missing busy_timeout:</strong> without it, a blocked connection fails at once instead of waiting.</li>
<li><strong>Forgotten open cursor:</strong> an unfinished <code>SELECT</code> keeps a read transaction alive. Fetch all rows or close the cursor.</li>
<li><strong>Exclusive locking mode:</strong> another process that set <code>locking_mode=EXCLUSIVE</code> can make other connections get <code>SQLITE_BUSY</code>.</li>
<li><strong>Network share:</strong> NFS or CIFS locking is unreliable. Move the file to local storage.</li>
</ol>
<h2 id="backups-replication-security-containers-and-upgrades">Backups, Replication, Security, Containers and Upgrades</h2>
<p>Back up a live SQLite database with the <strong>backup API (.backup) or VACUUM INTO</strong>, never by copying only the .db file of a WAL database, and test every restore. The rest of this section covers replication, storage, security, upgrades and monitoring.</p>
<h3>How Do You Back Up a Live SQLite Database?</h3>
<p>Both methods produce one consistent file while the app keeps serving traffic. Here are the two options in the sqlite3 shell:</p>
<p class="code-label"><strong>SQL (sqlite3 shell)</strong></p>
<pre><code class="language-sql">.backup 'backup.db'

VACUUM INTO 'backup.db';

-- SQLite 3.53+: URI target with reserve=N (0 to 255)
VACUUM INTO 'file:backup_reserved.db?reserve=32';</code></pre>
<p>✅ <code>.backup</code> uses the backup API. <code>VACUUM INTO</code> also writes a compacted copy, which is handy for archives.</p>
<p>Here is the same backup from Python, using <code>Connection.backup()</code>:</p>
<p class="code-label"><strong>Python</strong></p>
<pre><code class="language-python">import sqlite3

src = sqlite3.connect("app.db")
dst = sqlite3.connect("backup.db")
try:
    src.backup(dst)
finally:
    dst.close()
    src.close()</code></pre>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note: </strong>The backup API is like asking a clerk to photocopy a ledger together with the loose pages not yet filed into it. Copying only the .db file photocopies the bound book and ignores those pages.</p></blockquote>
<h3>Why Does Copying Only the .db File Fail?</h3>
<p>In WAL mode, the <code>-wal</code> and <code>-shm</code> files can hold committed data that is not yet in the main file. A copy of only <code>app.db</code> can therefore be stale or broken.</p>
<p>The animated diagram below shows a safe backup and restore test next to the unsafe file copy.</p>
<figure class="wp-block-image size-full"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/sqlite-best-practices-production-diagram-5.gif" alt="Pipeline: app with app.db, -wal and -shm feeds a backup job, then backup.db, object storage and a restore test. A red cp app.db path is stale." width="1200" height="675" /><figcaption>Back up with the backup API or VACUUM INTO and verify each restore; copying only app.db in WAL mode can miss committed data.</figcaption></figure>
<h3>How Do You Test a Restore?</h3>
<p>A backup is only proven when it opens and its data matches. Run these steps on a schedule:</p>
<ol>
<li><strong>Download:</strong> Fetch the latest backup into a scratch folder.</li>
<li><strong>Check integrity:</strong> Open it and run <code>PRAGMA integrity_check;</code>. The result should be <code>ok</code>.</li>
<li><strong>Compare counts:</strong> Check row counts of key tables (e.g. orders, customers) against expected values.</li>
<li><strong>Rehearse:</strong> Practice the full recovery, not just the check.</li>
</ol>
<h3>Is Litestream-Style Replication Worth It?</h3>
<p>Yes, if losing data since the last snapshot is not acceptable. Tools like Litestream stream WAL changes to object storage, so data loss is limited to the most recent changes. It needs WAL mode.</p>
<p>The trade-off is that this is backup and recovery, not a multi-writer cluster. Reads and writes still go through one primary file.</p>
<h3>How Do You Run SQLite in Docker and Kubernetes?</h3>
<p>Use a local volume or block storage attached to one pod. WAL relies on shared memory, so it is unreliable on NFS or CIFS.</p>
<ul>
<li><strong>Kubernetes:</strong> Use a StatefulSet with one replica and a dedicated persistent volume.</li>
<li><strong>Replicas:</strong> Never run several replicas that write the same file.</li>
<li><strong>Docker:</strong> Mount a local volume for the whole directory, so the <code>-wal</code> and <code>-shm</code> files stay with the database.</li>
</ul>
<h3>How Do You Secure a SQLite Database?</h3>
<p>Treat the file as the database server&#8217;s data directory. Anyone who can read it can read everything.</p>
<ul>
<li><strong>Permissions:</strong> Allow only the service account to access the file and the directory holding <code>-wal</code> and <code>-shm</code>.</li>
<li><strong>Encryption:</strong> Use an extension such as SQLCipher, or disk-level encryption.</li>
<li><strong>Queries:</strong> Always use bound parameters.</li>
</ul>
<p>Example: a clinic app stores patient notes in a local SQLite file. Encrypting the file, or the disk under it, means a stolen laptop or backup does not expose records.</p>
<h3>How Should You Handle SQLite Upgrades?</h3>
<p>Track patch releases. SQLite has no LTS line or fixed end-of-life dates, and only the newest line (3.54, latest 3.54.1 released 2026-10-16) is current. The 3.53.4 notes mention fixes for mostly AI-discovered bugs, so pinning an old version has a real cost.</p>
<p>Check the SQLite version bundled in your language driver, not just the OS package. They are often different.</p>
<h3>What Should You Monitor?</h3>
<ul>
<li><strong>WAL size:</strong> A growing <code>-wal</code> file points to long readers blocking checkpoints.</li>
<li><strong>Errors:</strong> Count busy and locked errors.</li>
<li><strong>Latency:</strong> Track query time.</li>
<li><strong>Disk:</strong> Alert on low free space.</li>
<li><strong>Backups:</strong> Alert when the last good backup is too old.</li>
</ul>
<h2 id="common-anti-patterns-and-production-readiness-checklist">Common Anti-Patterns and Production Readiness Checklist</h2>
<p>Most SQLite problems in production come from a few habits that work on a laptop and fail under real load. The table below lists the ten most common ones with the symptom you will see and the fix.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note: </strong> An anti-pattern is a habit that looks fine in testing but causes trouble under production load. It is like leaving a kitchen knife loose in a drawer: nothing happens until the day you reach in without looking.</p></blockquote>
<h3>Which SQLite Anti-Patterns Should You Avoid?</h3>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Anti-pattern</th>
<th>Symptom</th>
<th>Fix</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Default rollback journal under mixed load</strong></td>
<td>Readers and writers block each other</td>
<td>Enable SQLite WAL mode once at startup</td>
</tr>
<tr>
<td><strong>foreign_keys never enabled</strong></td>
<td>Orphan rows, no error on bad deletes</td>
<td>Run <code>PRAGMA foreign_keys=ON</code> on every connection</td>
</tr>
<tr>
<td><strong>Deferred transactions that write</strong></td>
<td>Instant SQLITE_BUSY, <code>busy_timeout</code> ignored</td>
<td>Start writes with <code>BEGIN IMMEDIATE</code></td>
</tr>
<tr>
<td><strong>One commit per row</strong></td>
<td>Slow bulk inserts</td>
<td>Batch rows in one transaction</td>
</tr>
<tr>
<td><strong>Database file on NFS</strong></td>
<td>Locking errors, unreliable WAL</td>
<td>Use a local disk or attached block storage</td>
</tr>
<tr>
<td><strong>Copying only the .db file</strong></td>
<td>Stale or broken backup</td>
<td>Use <code>.backup</code> or <code>VACUUM INTO</code></td>
</tr>
<tr>
<td><strong>Many app replicas sharing one file</strong></td>
<td>Frequent &#8220;database is locked&#8221; errors</td>
<td>Run one writer process, or move to PostgreSQL</td>
</tr>
<tr>
<td><strong>Non-STRICT tables with mixed types</strong></td>
<td>Text stored in integer columns</td>
<td>Create tables with <code>STRICT</code> (3.37+)</td>
</tr>
<tr>
<td><strong>Unbounded WAL growth from long readers</strong></td>
<td>The <code>-wal</code> file keeps growing</td>
<td>Keep reads short, run <code>wal_checkpoint(TRUNCATE)</code> when quiet</td>
</tr>
<tr>
<td><strong>Pinning an old SQLite version forever</strong></td>
<td>Known bugs stay in your build</td>
<td>Track patch releases, currently 3.54.1</td>
</tr>
</tbody>
</table>
</figure>
<h3>What Is the SQLite Production Readiness Checklist?</h3>
<p>Work through these steps in order before you run SQLite in production.</p>
<ol>
<li><strong>Confirm fit:</strong> the app and file share one machine, and you have written down your PostgreSQL migration triggers.</li>
<li><strong>Check the driver version:</strong> find the SQLite version bundled with your language driver, not just the OS package.</li>
<li><strong>Turn on WAL:</strong> set <code>journal_mode=WAL</code> in a startup or migration step.</li>
<li><strong>Set PRAGMAs per connection:</strong> apply <code>synchronous</code>, <code>busy_timeout</code>, <code>foreign_keys</code> and <code>cache_size</code> in the connection factory.</li>
<li><strong>Use a STRICT schema:</strong> add constraints and indexes that match your filters.</li>
<li><strong>Serialize writes:</strong> use <code>BEGIN IMMEDIATE</code> with one writer connection or a mutex.</li>
<li><strong>Keep storage local:</strong> no NFS or CIFS, and one writer pod in Kubernetes.</li>
<li><strong>Schedule backups:</strong> use the backup API and test restores with <code>PRAGMA integrity_check</code>.</li>
<li><strong>Monitor:</strong> watch <code>-wal</code> size, busy errors, free disk and backup age.</li>
<li><strong>Patch regularly:</strong> set a routine to update to new SQLite releases.</li>
</ol>
<h2 id="key-takeaways">Key takeaways</h2>
<p>Here are the main points to remember when you run SQLite in production:</p>
<ul>
<li><strong>Check the fit first:</strong> SQLite is production-ready when the app and the database file live on the same machine and writes fit a single-writer model. Move to PostgreSQL when several app servers need the same data or writes keep queueing even after batching.</li>
<li><strong>Use WAL and set PRAGMAs on every connection:</strong> <code>journal_mode=WAL</code> is saved in the file, but <code>synchronous</code>, <code>busy_timeout</code>, <code>foreign_keys</code> and <code>cache_size</code> must be applied each time you open a connection. Put them in one connection factory.</li>
<li><strong>Use BEGIN IMMEDIATE for writes:</strong> A deferred transaction that upgrades to a writer can fail with SQLITE_BUSY right away, and <code>busy_timeout</code> will not help. Take the write lock up front, serialize writes in the app, and keep transactions short.</li>
<li><strong>Design the schema strictly:</strong> Use STRICT tables, <code>INTEGER PRIMARY KEY</code>, indexes that match your filters, bound parameters, and one transaction per batch instead of one commit per row.</li>
<li><strong>Back up with the right tools:</strong> Use <code>.backup</code>, the backup API or <code>VACUUM INTO</code>. Never copy only the <code>.db</code> file of a WAL database, and test every restore with <code>PRAGMA integrity_check</code> and row counts.</li>
<li><strong>Keep the file on local disk:</strong> WAL needs shared memory, so avoid NFS and CIFS. In Docker or Kubernetes use a local volume or block storage attached to a single pod, and never run several replicas that write the same file.</li>
<li><strong>Track patch releases:</strong> SQLite has no LTS line or fixed end-of-life dates, and only the newest line (3.54, latest 3.54.1) is current. Check the SQLite version bundled with your language driver, not just the OS package.</li>
</ul>
<p>That&#8217;s all! Happy coding!</p>
<p>Did this solve the issue you were facing? Please share your questions or experience in the comments below. If you found this guide useful, bookmark it and share it with your team. Subscribe to TheCodeBuzz to get new database best-practice articles in your inbox.</p>
<h2 id="faq">FAQ</h2>
<h3><strong>Is SQLite good enough for production?</strong></h3>
<p>Yes, when the application and the database file are on the same machine and your writes can run through a single serialized writer. Turn on WAL mode, set the per-connection PRAGMAs, and keep write transactions short. If several app servers need the same data over a network, a client/server database is the better choice.</p>
<h3><strong>When should I use SQLite instead of PostgreSQL or MySQL?</strong></h3>
<p>Use SQLite for embedded and IoT devices, local data files, data analysis, caches of enterprise data, and small to medium sites that run on one server. It works best when simple administration matters more than enterprise features. Choose PostgreSQL or MySQL when many client programs send SQL to the same database over a network, or when you need built-in streaming replication or fine-grained roles.</p>
<h3><strong>How many concurrent writers can SQLite handle?</strong></h3>
<p>One at a time. In WAL mode, many readers can run alongside that single writer, and a second writer waits until the first commits or rolls back. Real write throughput depends on how well you batch rows into transactions and on how fast your disk syncs, so measure it on your own hardware.</p>
<h3><strong>How do I fix &#8216;database is locked&#8217; (SQLITE_BUSY) errors?</strong></h3>
<p>Start by setting <code>busy_timeout</code> on every connection, so a waiting writer retries instead of failing at once. Then use <code>BEGIN IMMEDIATE</code> for any transaction that writes, keep transactions short, and send all writes through one writer connection or a mutex. If errors continue, look for long-running read transactions, open cursors that were never closed, and a database file on a network share.</p>
<h3><strong>How do I back up a SQLite database that is in use?</strong></h3>
<p>Use the <code>.backup</code> command in the sqlite3 shell (it uses the backup API) or <code>VACUUM INTO 'backup.db'</code>. Both give a consistent copy while the app keeps running. Don&#8217;t copy only the <code>.db</code> file of a WAL database, because the <code>-wal</code> and <code>-shm</code> files can hold committed data that isn&#8217;t in the main file yet. After each backup, open the copy and run <code>PRAGMA integrity_check</code> to confirm it is usable.</p>
<h2 id="sources">Sources and further reading</h2>
<ul>
<li><a href="https://www.sqlite.org/news.html" target="_blank" rel="noopener">Recent SQLite News</a> (SQLite.org)</li>
<li><a href="https://www.sqlite.org/releaselog/3_53_4.html" target="_blank" rel="noopener">SQLite Release 3.53.4 On 2026-07-24</a> (SQLite.org)</li>
<li><a href="https://www.sqlite.org/wal.html" target="_blank" rel="noopener">Write-Ahead Logging</a> (SQLite.org)</li>
<li><a href="https://www.sqlite.org/whentouse.html" target="_blank" rel="noopener">Appropriate Uses For SQLite</a> (SQLite.org)</li>
<li><a href="https://www.versio.io/en/product-release-end-of-life-eol-sqlite-team-sqlite.html" target="_blank" rel="noopener">SQLite releases, versions &amp; end-of-life (EOL) dates</a> (versio.io)</li>
</ul>
<p><em>Diagrams are original illustrations created for TheCodeBuzz.</em></p><p>The post <a href="https://thecodebuzz.com/sqlite-best-practices-production/">SQLite Best Practices for Production: WAL, PRAGMA, Backups</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/sqlite-best-practices-production/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Cosmos DB Best Practices: Partitioning, RU and Consistency</title>
		<link>https://thecodebuzz.com/cosmos-db-best-practices-partitioning/</link>
					<comments>https://thecodebuzz.com/cosmos-db-best-practices-partitioning/#respond</comments>
		
		<dc:creator><![CDATA[Izzy]]></dc:creator>
		<pubDate>Wed, 11 Nov 2026 14:59:46 +0000</pubDate>
				<category><![CDATA[Database Best Practices]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Cosmos DB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Partition Key]]></category>
		<category><![CDATA[Request Units]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=30995</guid>

					<description><![CDATA[<p>Cosmos DB best practices for production: choose a partition key, fix hot partitions, cut RU cost, handle 429 errors and pick a consistency level.</p>
<p>The post <a href="https://thecodebuzz.com/cosmos-db-best-practices-partitioning/">Cosmos DB Best Practices: Partitioning, RU and Consistency</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Today in this article, we will see a practical Cosmos DB best practices guide for Azure Cosmos DB for NoSQL, covering partition keys, RU optimization and <a href="https://thecodebuzz.com/cassandra-best-practices-guidelines/">consistency levels</a>. It is written for engineers, architects and DBAs who run Cosmos DB in production or are about to.</p>
<p>Three decisions drive most production problems. The first is the <strong>partition key</strong>, which cannot be changed in place once a container exists. The second is the <strong>RU cost of each operation</strong>, since every read and write is billed in Request Units. The third is the <strong>consistency level</strong>, which trades read freshness against latency and availability.</p>
<p>The guide starts with an at-a-glance table. It then covers partition keys and hierarchical partition keys, hot partitions and <a href="https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/">data modeling</a>, and RU and 429 handling with .NET SDK v3 code. After that come consistency levels, followed by anti-patterns, a production readiness checklist and a migration note. You will not find generic savings figures here. Instead, the guide shows you how to measure your own RU numbers, because the cost depends on your data and queries.</p>
<p>Before we start, you need an existing Cosmos DB for NoSQL account and the .NET SDK v3 (<code>Microsoft.Azure.Cosmos</code>). The current SDK version was not confirmed while writing, so check NuGet for the latest release.</p>
<blockquote><p><strong>Version note:</strong> This guide targets Azure Cosmos DB for NoSQL (a managed service with no user-facing version number, with features announced up to Build 2026 in June 2026) and the .NET SDK v3 (Microsoft.Azure.Cosmos), whose current version you should confirm on NuGet.</p>
<p>&nbsp;</p>
<p><strong>In this guide</strong></p></blockquote>
<ul>
<li><a href="#cosmos-db-best-practices-at-a-glance">Cosmos DB Best Practices at a Glance</a></li>
<li><a href="#cosmos-db-partition-key-best-practices">Cosmos DB Partition Key Best Practices</a></li>
<li><a href="#fix-a-cosmos-db-hot-partition-with-a-better-data-model">Fix a Cosmos DB Hot Partition with a Better Data Model</a></li>
<li><a href="#cosmos-db-ru-optimization-and-429-throttling">Cosmos DB RU Optimization and 429 Throttling</a></li>
<li><a href="#cosmos-db-consistency-levels-choose-and-override">Cosmos DB Consistency Levels: Choose and Override</a></li>
<li><a href="#common-anti-patterns-operations-and-production-readiness-che">Common Anti-Patterns, Operations and Production Readiness Checklist</a></li>
<li><a href="#key-takeaways">Key takeaways</a></li>
<li><a href="#faq">FAQ</a></li>
</ul>
<h2 id="cosmos-db-best-practices-at-a-glance">Cosmos DB Best Practices at a Glance</h2>
<p>Most Cosmos DB problems come from a weak partition key, expensive queries and the wrong consistency level. The table below sums up the rules for Cosmos DB cost optimization and performance.</p>
<p>Here is a quick reference of what to do and what to avoid in each area:</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Area</th>
<th>Do this</th>
<th>Avoid this</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Partition key</strong></td>
<td>Pick a high-cardinality key that spreads storage and RU use evenly. Keep each logical partition under 20 GB, unless you use a hierarchical key that ends in <code>/id</code>, which lets the earlier levels grow past that limit.</td>
<td>Low-cardinality or purely time-based keys.</td>
</tr>
<tr>
<td><strong>Hierarchical keys</strong></td>
<td>Use up to three levels, each with high cardinality, ordered by filter use.</td>
<td>A first level that only a few values ever touch.</td>
</tr>
<tr>
<td><strong>Data model</strong></td>
<td>Colocate related entity types in one container or a few.</td>
<td>One container per entity type.</td>
</tr>
<tr>
<td><strong>Reads</strong></td>
<td>Use point reads (id plus partition key). Project only the fields you need.</td>
<td><code>SELECT *</code> and cross-partition queries.</td>
</tr>
<tr>
<td><strong>Indexing policy</strong></td>
<td>Exclude paths you never filter or sort on.</td>
<td>Indexing everything on write-heavy data.</td>
</tr>
<tr>
<td><strong>Throughput mode</strong></td>
<td>Match RU/s to the real workload shape.</td>
<td>Paying for peak capacity all day.</td>
</tr>
<tr>
<td><strong>429 handling</strong></td>
<td>Honor the retry-after value and tune SDK retry settings.</td>
<td>Adding RU/s to fix a hot partition.</td>
</tr>
<tr>
<td><strong>Consistency</strong></td>
<td>Choose the weakest account default your correctness rules allow. Relax it per request for reads that can tolerate it.</td>
<td>Strong consistency everywhere.</td>
</tr>
<tr>
<td><strong>Monitoring</strong></td>
<td>Log the RU charge from every response.</td>
<td>Guessing where RUs go.</td>
</tr>
<tr>
<td><strong>Migration</strong></td>
<td>Decide the key early. Copy data to a new container if it must change.</td>
<td>Expecting an in-place key change.</td>
</tr>
</tbody>
</table>
</figure>
<p>Each row is explained with its reason in the sections below.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>In plain English:</strong> A Request Unit (RU) is one normalized currency for the CPU, IO and memory an operation needs. Think of it like a restaurant bill: reading one small item is a cheap dish, a large query is a full banquet, and your throughput is the budget per second.</p></blockquote>
<h2 id="cosmos-db-partition-key-best-practices">Cosmos DB Partition Key Best Practices</h2>
<p>Choose a partition key with <strong>high cardinality</strong> (many distinct values) that spreads both storage and RU use evenly and appears in your most common query filters. The key is hard to change later, so it deserves the most design time of any Cosmos DB decision.</p>
<h3>What Is the Difference Between a Logical and a Physical Partition?</h3>
<p>A <strong>logical partition</strong> holds all items that share the same partition key value, and it is limited to 20 GB. A <strong>physical partition</strong> is the storage and compute unit that hosts one or more logical partitions. You control the first, and Cosmos DB manages the second.</p>
<blockquote><p><strong>In plain English:</strong> Think of a library. Each logical partition is a shelf of labelled books, and each physical partition is a room that holds several shelves. You choose the labels, and the library decides which room each shelf goes in. Unlike a real shelf, a logical partition can never grow past its 20 GB limit.</p></blockquote>
<h3>How Do You Know a Partition Key Is Good?</h3>
<p>A good key passes four checks. Test your candidate against each one before you create the container.</p>
<ul>
<li><strong>High cardinality:</strong> many distinct values mean many small logical partitions that can be spread across physical partitions.</li>
<li><strong>Even request distribution:</strong> no value should receive far more reads or writes than the others, or one partition throttles while the rest sit idle.</li>
<li><strong>Even storage distribution:</strong> no value should approach the 20 GB logical partition limit.</li>
<li><strong>Used in filters:</strong> a query that includes the key stays in one partition. Without it, the query becomes a cross-partition query that fans out to every partition and costs more RUs.</li>
</ul>
<p>The animated diagram below walks through these checks as a decision tree, from your top queries to a single-property key, a hierarchical key, or a data model rework.</p>
<figure class="wp-block-image size-full"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/10/cosmos-db-best-practices-partitioning-diagram-2.gif" alt="Decision tree: test filters, cardinality, and spread to pick a single-property key, a hierarchical key, or rework the data model." width="1200" height="675" /><figcaption>Work through steps 1 to 3 in order; each answer leads to a single key, a hierarchical key, or a data model rework.</figcaption></figure>
<h3>Worked Example: Which Key Fits an IoT Workload?</h3>
<p>Microsoft&#8217;s IoT partitioning example compares three options for a system ingesting data from more than 50K devices. Only the third passes every check.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Candidate key</th>
<th>Result</th>
<th>Reason</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>DeviceId only</strong></td>
<td>Rejected</td>
<td>Data from a device keeps accumulating, so with 50K+ devices there is a risk of hitting the 20 GB limit.</td>
</tr>
<tr>
<td><strong>Time-based only</strong></td>
<td>Rejected</td>
<td>All current writes land in one partition.</td>
</tr>
<tr>
<td><strong>DeviceId plus time-based second level</strong></td>
<td>Chosen</td>
<td>Balances even distribution with efficient queries.</td>
</tr>
</tbody>
</table>
</figure>
<h3>When Should You Use Hierarchical Partition Keys?</h3>
<p>Use <strong>Cosmos DB hierarchical partition keys</strong> when one property cannot satisfy the checks alone. They are generally available and allow up to three levels (e.g. TenantId, UserId, SessionId). They replace many synthetic-key designs, especially in multi-tenant workloads.</p>
<ul>
<li><strong>Keep every level high cardinality:</strong> this applies from the first level onward.</li>
<li><strong>Watch the first level&#8217;s real traffic:</strong> a first level that looks high cardinality can still be hot if the workload touches only a few values.</li>
<li><strong>Order levels by filter use:</strong> put the level that appears most often in your filters first, in the order you filter on them.</li>
</ul>
<p>Items that share the same first-level value sit on the same physical partition, so queries on that value avoid a full fan-out. If the key ends with a unique value such as <code>/id</code>, the earlier levels can grow past 20 GB. No account-level setting is needed.</p>
<p>The code below creates a container with a three-level key (TenantId, UserId, id) and reads one item by building the full key. Use a recent version of the <code>Microsoft.Azure.Cosmos</code> package from NuGet.</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">using Microsoft.Azure.Cosmos;

CosmosClient client = new CosmosClient(endpoint, key);
Database database = client.GetDatabase("appdb");

ContainerProperties properties = new ContainerProperties(
    id: "sessions",
    partitionKeyPaths: new List&lt;string&gt; { "/TenantId", "/UserId", "/id" });

ContainerResponse created =
    await database.CreateContainerIfNotExistsAsync(properties, throughput: 400);
Container container = created.Container;

PartitionKey partitionKey = new PartitionKeyBuilder()
    .Add("tenant-42")
    .Add("user-1001")
    .Add("session-9")
    .Build();

ItemResponse&lt;Session&gt; response =
    await container.ReadItemAsync&lt;Session&gt;("session-9", partitionKey);

public record Session(string id, string TenantId, string UserId);</code></pre>
<p>The <code>PartitionKeyBuilder</code> values follow the path order, and the last value matches the item&#8217;s <code>id</code>.</p>
<blockquote><p><strong>Warning:</strong> You cannot change the partition key of an existing container in place. To change it, create a new container with the right key and copy the data across, so decide early and test your key against real access patterns first.</p></blockquote>
<h2 id="fix-a-cosmos-db-hot-partition-with-a-better-data-model">Fix a Cosmos DB Hot Partition with a Better Data Model</h2>
<p>A <strong>Cosmos DB hot partition</strong> is one partition that takes far more RU or storage than the others. It starts to throttle while the rest of the container sits idle.</p>
<blockquote><p><strong>In plain English:</strong> Picture a supermarket with ten checkout lanes where every customer joins lane one. Lane one has a long queue while nine cashiers wait. Adding more cashiers doesn&#8217;t help, because customers still pick the same lane.</p></blockquote>
<h3>How do you detect a hot partition?</h3>
<p>Compare partition-level metrics with the container-wide numbers in Azure Monitor (Metrics). Look at normalized RU consumption split by partition.</p>
<ul>
<li><strong>Skew pattern:</strong> a few partitions sit near 100% while the container average stays low. This points to a skewed key, not a lack of capacity.</li>
<li><strong>Matching symptom:</strong> 429 responses appear even though total consumption looks well below what you provisioned.</li>
</ul>
<h3>Why doesn&#8217;t raising RU/s fix it?</h3>
<p>Provisioned throughput is divided across physical partitions, so the hot partition still gets only its own share. Extra RU/s mostly pays for capacity the idle partitions never use. That is why this is a data model problem first and a Cosmos DB cost optimization problem second.</p>
<p>A Cosmos DB Conf 2026 production lesson shows this. One logical partition took over 80% of traffic. After the data model was fixed, with no extra scaling, RU utilization fell to 20-35% and throttling stopped.</p>
<h3>What should you change in the data model?</h3>
<p>Change the key or the shape of the data, in this order of preference:</p>
<ol>
<li><strong>Pick a higher-cardinality key:</strong> choose a property with many distinct values that your workload actually touches evenly.</li>
<li><strong>Use hierarchical partition keys:</strong> add levels such as TenantId, UserId, id so one large tenant spreads across many partitions.</li>
<li><strong>Add a spreading level:</strong> a time bucket (e.g. day or month) stops current writes from landing on one value.</li>
<li><strong>Split read and write shapes:</strong> when one key can&#8217;t serve both, use the design below.</li>
</ol>
<h3>Should you colocate entity types in one container?</h3>
<p>Yes, colocate related entity types in one container, or a small number of containers. Queries are scoped to one container, and multi-item atomic transactions (stored procedures and triggers) are scoped to one partition key in one container. Colocation also cuts network round trips.</p>
<p>If you can&#8217;t colocate, for example when migrating an existing app unchanged, consider database-level shared throughput.</p>
<h3>What is the write-optimized container with change feed design?</h3>
<p>Write to one container whose key spreads writes evenly. Then feed other containers through the change feed, each keyed for one read pattern. The animated diagram below shows this flow.</p>
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/10/cosmos-db-best-practices-partitioning-diagram-3.gif" alt="Writes enter an Orders container, the change feed processor copies items to containers keyed by CustomerId and ProductId, and reads hit them." width="1200" height="675" /><figcaption>Writes land in one evenly partitioned container; the change feed builds read models so each query stays single-partition.</figcaption></figure>
<p>Example: a retail orders container is partitioned for even writes. The change feed processor copies each order into one container keyed by CustomerId and another keyed by ProductId. Both read paths then run as single-partition queries.</p>
<p>Microsoft announced the All Versions and Deletes change feed mode as generally available at Build 2026. Confirm its status in the announcement before you rely on it.</p>
<p><strong>Trade-off:</strong> read-model containers add storage cost and eventual lag, since copies arrive after the write. Use them only when one partition key cannot serve both access patterns.</p>
<h2 id="cosmos-db-ru-optimization-and-429-throttling">Cosmos DB RU Optimization and 429 Throttling</h2>
<p>To <strong>reduce Cosmos DB request units</strong>, use point reads instead of queries, keep queries inside one partition, project only the fields you need and trim the indexing policy. Each of these lowers the RU charge, and RU charge drives both cost and throttling.</p>
<h3>How Do You Measure Cosmos DB RU Cost?</h3>
<p>Read the <code>RequestCharge</code> from every response. The same query on the same data always costs the same RUs, so the number is repeatable and safe to compare before and after a change.</p>
<p>Query execution metrics show where the RUs went. Paged results are charged per page, and the pages add up to the cost of the whole query. Measure your own workload instead of copying generic savings figures.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>In plain English:</strong> An RU is like a price tag on each operation. A cheap lookup costs a few coins, a big scan costs many, and your provisioned RU/s is the coins you get each second.</p></blockquote>
<h3>Point Read vs Query: Which Costs Less?</h3>
<p>A point read is the cheapest way to fetch one item. The table compares the three access shapes.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Operation</th>
<th>Needs</th>
<th>Cost behavior</th>
<th>Use when</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Point read</strong></td>
<td>id and partition key</td>
<td>Lowest for one item</td>
<td>You know both values</td>
</tr>
<tr>
<td><strong>Single-partition query</strong></td>
<td>Partition key in the filter</td>
<td>Grows with items scanned and returned</td>
<td>You need a list inside one key value</td>
</tr>
<tr>
<td><strong>Cross-partition query</strong></td>
<td>Partition key not in the filter</td>
<td>Grows with the number of partitions touched and how selective the filter is; a query that fans out to many partitions costs more than the same query scoped to one</td>
<td>Rare, admin or reporting needs</td>
</tr>
</tbody>
</table>
</figure>
<p>Query cost depends on the number and kind of predicates, the number of UDFs and the size of the source data. A query returning a thousand 1-KB items costs about 1,000 RUs, so at 1,000 RU/s you get roughly one such query per second before throttling. Use <code>SELECT c.id, c.name, c.price</code> instead of <code>SELECT *</code>.</p>
<p><strong>Use case:</strong> A retail catalog service serves product pages by id and category. With category as the partition key, the product page is a point read, and the category listing is a single-partition query.</p>
<h3>How Do You Trim the Indexing Policy?</h3>
<p><a href="https://thecodebuzz.com/mongodb-indexes-performance-guidelines-and-best-practices/">Exclude paths you never filter</a> or sort on. Every indexed path is maintained on each write, so fewer paths mean fewer write RUs.</p>
<p class="code-label"><strong>JSON</strong></p>
<pre><code class="language-json">{
  "indexingMode": "consistent",
  "includedPaths": [ { "path": "/*" } ],
  "excludedPaths": [ { "path": "/descriptionHtml/*" } ]
}</code></pre>
<p>This simplified policy indexes everything except a large, unused description field.</p>
<h3>Which Throughput Mode Should You Use?</h3>
<p>Throughput is set at container level or shared at database level, and you can change it at any time. You pay for what you configure, so match RU/s to the real workload shape. Verify current limits on the pricing page.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Mode</th>
<th>How it works</th>
<th>Use when</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Manual provisioned</strong></td>
<td>You set a fixed RU/s</td>
<td>Traffic is steady and predictable</td>
</tr>
<tr>
<td><strong>Autoscale</strong></td>
<td>RU/s adjusts within a range you set</td>
<td>Traffic varies or has peaks</td>
</tr>
<tr>
<td><strong>Serverless</strong></td>
<td>You pay per request, with no provisioned RU/s</td>
<td>Traffic is small or occasional, e.g. dev and test</td>
</tr>
</tbody>
</table>
</figure>
<h3>What Happens When Cosmos DB Returns 429?</h3>
<p>When a request exceeds provisioned throughput, the service ends it with <strong>HTTP 429 (RequestRateTooLarge)</strong> and an <code>x-ms-retry-after-ms</code> header with the wait time in milliseconds. The SDK retry settings decide how many retries happen before the exception reaches your app.</p>
<p>The animated diagram below shows how a throttled request is retried, and what happens when retries run out.</p>
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/10/cosmos-db-best-practices-partitioning-diagram-4.gif" alt="Sequence across Application, SDK and service lanes: request gets 429, SDK waits, retry returns 200; alternate path ends in CosmosException." width="1200" height="675" /><figcaption>The SDK honors x-ms-retry-after-ms and retries; once retry limits are hit, the 429 CosmosException reaches your code.</figcaption></figure>
<p>Workloads that aren&#8217;t latency-sensitive can run with less throughput and rely on this rate limiting. If 429s come from one hot partition, fix the key. More RU/s is split across partitions and won&#8217;t help.</p>
<h3>How Do You Log RU Charge and Handle 429 in .NET?</h3>
<p>Check NuGet for the current <code>Microsoft.Azure.Cosmos</code> version before you start. First, set the retry options on the client:</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">// Run this once at application startup, not per request.
var client = new CosmosClient(connectionString, new CosmosClientOptions
{
    MaxRetryAttemptsOnRateLimitedRequests = 5,
    MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(10)
});
Container container = client.GetContainer("retail", "products");</code></pre>
<p>The SDK stops retrying a throttled call once it has made 5 retries or waited 10 seconds in total, whichever comes first, and then throws.</p>
<p><strong>Create one <code>CosmosClient</code> per application lifetime and reuse it.</strong> The client is designed to be shared and is thread-safe, so register it as a singleton (e.g. in your dependency injection container) and inject the <code>Container</code> where needed. Creating a new client for every request wastes connections and adds startup cost to each call. The snippet above shows the client only to demonstrate the options, and the later examples assume the same shared <code>container</code>.</p>
<p>The values 5 and 10 seconds are example settings, not the SDK defaults. The research notes don&#8217;t list the default values, so check the current Cosmos DB .NET SDK documentation for them. Raising the limits makes the SDK wait longer and hide more throttling from your app, and lowering them makes 429 exceptions reach your code sooner. Pick values that fit how long a caller can wait.</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">public record Product(string id, string category, string name, decimal price);

ItemResponse&lt;Product&gt; response = await container.ReadItemAsync&lt;Product&gt;(
    "sku-1001", new PartitionKey("shoes"));
Console.WriteLine($"Point read RU: {response.RequestCharge}");</code></pre>
<p>This point read logs its own RU charge.</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">public record ProductSummary(string id, string name, decimal price);

var query = new QueryDefinition(
    "SELECT c.id, c.name, c.price FROM c WHERE c.category = @category")
    .WithParameter("@category", "shoes");
var options = new QueryRequestOptions { PartitionKey = new PartitionKey("shoes") };

double totalRu = 0;
using FeedIterator&lt;ProductSummary&gt; iterator =
    container.GetItemQueryIterator&lt;ProductSummary&gt;(query, requestOptions: options);
while (iterator.HasMoreResults)
{
    FeedResponse&lt;ProductSummary&gt; page = await iterator.ReadNextAsync();
    totalRu += page.RequestCharge;
}
Console.WriteLine($"Query RU: {totalRu}");</code></pre>
<p>This single-partition query projects three fields and adds up the charge for every page.</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">try
{
    await container.ReadItemAsync&lt;Product&gt;("sku-1001", new PartitionKey("shoes"));
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
{
    Console.WriteLine($"Throttled. Retry after: {ex.RetryAfter}");
    Console.WriteLine(ex.Diagnostics.ToString());
    // Back off here before trying again.
}</code></pre>
<p>This catch block runs only after the SDK has used up its retries, so log the diagnostics and back off.</p>
<h2 id="cosmos-db-consistency-levels-choose-and-override">Cosmos DB Consistency Levels: Choose and Override</h2>
<p>Cosmos DB offers five consistency levels: Strong, Bounded Staleness, Session, Consistent Prefix and Eventual. <strong>Session is the default</strong>. Pick the weakest level your correctness rules allow for each read, because stronger levels cost more.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>In plain English:</strong> Consistency is how quickly an update you save shows up for everyone else. Think of a news site: one screen shows the new headline, and consistency decides how long another screen may still show the old one. Unlike a news site, Cosmos DB lets you choose that wait.</p></blockquote>
<h3>What Does Each Consistency Level Guarantee?</h3>
<p>The table below describes what a reader sees at each level and where it fits.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Level</th>
<th>What readers see</th>
<th>Typical use case</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Strong</strong></td>
<td>Always the latest committed write</td>
<td>Account balances, inventory that cannot oversell</td>
</tr>
<tr>
<td><strong>Bounded Staleness</strong></td>
<td>Data that lags by a limited amount, never more</td>
<td>Dashboards that tolerate a known delay</td>
</tr>
<tr>
<td><strong>Session</strong></td>
<td>Your own writes, in order, within your session</td>
<td>Most apps, e.g. shopping cart, user profile</td>
</tr>
<tr>
<td><strong>Consistent Prefix</strong></td>
<td>Updates in order, but possibly behind</td>
<td>Activity feeds where order matters</td>
</tr>
<tr>
<td><strong>Eventual</strong></td>
<td>No ordering promise, converges later</td>
<td>Like counts, view counts</td>
</tr>
</tbody>
</table>
</figure>
<h3>What Are the Trade-offs?</h3>
<p>Stronger levels add latency and reduce availability. Strong is also not available when the account uses multi-region writes. <strong>Strong and Bounded Staleness reads cost more RUs than reads at the weaker levels</strong>, so a stricter default has a price on every read that does not override it.</p>
<p>The size of that difference depends on your data and access pattern. Measure <code>RequestCharge</code> for your own reads at each level instead of trusting a generic figure.</p>
<h3>How Do You Override Consistency Per Request?</h3>
<p>You can set the consistency level on a single request with <code>ItemRequestOptions.ConsistencyLevel</code>. The rule is simple: <strong>a per-request override can only be equal to or weaker than the account default, never stronger</strong>.</p>
<p>This means the account default is your ceiling. If the default is Session, you cannot raise a single request to Strong. To have any request read at Strong, the account default itself must be Strong.</p>
<p>So the design works in one direction. Set the account default to the strictest level your most sensitive reads need, then relax it per request for reads that can tolerate staleness. Here is a simplified example for a retail review feed:</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">var options = new ItemRequestOptions
{
    ConsistencyLevel = ConsistencyLevel.Eventual
};

ItemResponse&lt;Review&gt; response = await container.ReadItemAsync&lt;Review&gt;(
    id: "review-1001",
    partitionKey: new PartitionKey("product-42"),
    requestOptions: options);

Console.WriteLine($"RU charge: {response.RequestCharge}");</code></pre>
<p>This reads one review at Eventual consistency, which is weaker than any account default, and logs its RU charge so you can compare levels.</p>
<blockquote><p><strong>Example:</strong> A banking service sets the account default to Strong, because balance checks must always see the latest committed write (this needs an account without multi-region writes). Reads that tolerate delay, such as a statement history page, relax to Session or Eventual on each request to save latency and RUs. A retail product-review feed relaxes to Eventual the same way, since a review appearing a few seconds late harms nobody.</p></blockquote>
<h2 id="common-anti-patterns-operations-and-production-readiness-che">Common Anti-Patterns, Operations and Production Readiness Checklist</h2>
<p>Most production incidents trace back to a few repeated design mistakes. The table below lists each one with the symptom you will see and the fix.</p>
<h3>Which Cosmos DB anti-patterns cause the most trouble?</h3>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Anti-pattern</th>
<th>Symptom</th>
<th>Fix</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Low-cardinality or time-only key</strong></td>
<td>One partition takes all writes or nears 20 GB</td>
<td>Use a high-cardinality or hierarchical key</td>
</tr>
<tr>
<td><strong>Key not used in filters</strong></td>
<td>Cross-partition fan-out, high RU per query</td>
<td>Pick a key your common filters contain</td>
</tr>
<tr>
<td><strong>SELECT * and queries instead of point reads</strong></td>
<td>High RequestCharge for simple lookups</td>
<td>Use <code>ReadItemAsync</code>, project only needed fields</td>
</tr>
<tr>
<td><strong>One container per entity type</strong></td>
<td>Many round trips, no cross-entity transactions</td>
<td>Colocate related entities</td>
</tr>
<tr>
<td><strong>Default indexing on write-heavy data</strong></td>
<td>High write RU cost</td>
<td>Exclude paths you never filter or sort on</td>
</tr>
<tr>
<td><strong>Raising RU/s to fix a hot partition</strong></td>
<td>429s continue, cost rises</td>
<td>Fix the key or data model</td>
</tr>
<tr>
<td><strong>Never logging RequestCharge</strong></td>
<td>Cost surprises with no cause</td>
<td>Log charge and diagnostics per operation</td>
</tr>
<tr>
<td><strong>Strong consistency everywhere</strong></td>
<td>Higher latency, less availability</td>
<td>Set the default to the weakest level that is acceptable and relax per request</td>
</tr>
</tbody>
</table>
</figure>
<blockquote><p><strong>In plain English:</strong> A cross-partition query is like asking every room in a library to search its shelves for you. A good key sends you to the one room that holds your book.</p></blockquote>
<h3>What should you monitor in production?</h3>
<p>Watch three signals: normalized RU consumption, 429 counts and provisioned RU/s.</p>
<ul>
<li><strong>Normalized RU consumption:</strong> check it per partition, not only as a container average, to spot skew.</li>
<li><strong>429 counts:</strong> a steady stream means a hot partition or too little throughput.</li>
<li><strong>Provisioned RU/s:</strong> match it to the real shape of your workload. This is the main lever for Cosmos DB cost optimization.</li>
</ul>
<h3>How do you migrate to a new partition key?</h3>
<p>You can&#8217;t change the partition key of an existing container in place. Create a new container with the right key, copy the data (e.g. with change feed or a bulk copy job) and cut over. Test the whole process on a copy first.</p>
<h3>Which recent features need a status check?</h3>
<p>Build 2026 (June 2026) announced the Linux Emulator and the All Versions and Deletes change feed mode as generally available, along with Global Secondary Indexes. Verify each feature&#8217;s status in the announcement before you depend on it.</p>
<h3>Production readiness checklist</h3>
<p>Work through these steps in order before go-live:</p>
<ol>
<li><strong>Model access patterns:</strong> list your reads, writes and filters first.</li>
<li><strong>Choose and load-test the partition key:</strong> use realistic data and traffic.</li>
<li><strong>Confirm 20 GB headroom:</strong> check that no logical partition value can outgrow the limit.</li>
<li><strong>Colocate entities:</strong> group related types in one container where queries and transactions need it.</li>
<li><strong>Trim the indexing policy:</strong> exclude unused paths.</li>
<li><strong>Log RequestCharge:</strong> record it for every operation.</li>
<li><strong>Use a singleton CosmosClient:</strong> create one client per application and reuse it for all requests, instead of creating a new client per call. The client holds the connections and the retry settings, so sharing it keeps behavior consistent.</li>
<li><strong>Set SDK retry options:</strong> configure the retry count and maximum wait on that single client.</li>
<li><strong>Consider preferred regions and direct mode (optional):</strong> if your account has more than one region, set the preferred regions list so the SDK reads from the closest one. Also review the SDK&#8217;s connection mode (direct or gateway) for your workload. Check the current SDK documentation for the exact options.</li>
<li><strong>Alert on 429s and partition skew:</strong> watch both.</li>
<li><strong>Relax consistency per request where staleness is acceptable:</strong> set the account default to the weakest level your correctness rules allow. Then relax individual reads that tolerate stale data, for example a product-review feed. A request can only use a level equal to or weaker than the default, so confirm this rule on the official consistency-levels page.</li>
<li><strong>Rehearse migration and restore:</strong> prove you can recover before you must.</li>
</ol>
<h2 id="key-takeaways">Key takeaways</h2>
<p>These are the points to remember from this guide, in the order you will likely need them when designing or fixing a Cosmos DB workload:</p>
<ul>
<li><strong>Choose the partition key from access patterns:</strong> pick a key with high cardinality that spreads both storage and RU use evenly and appears in your most common query filters. Keep each logical partition well under the 20 GB limit.</li>
<li><strong>Use hierarchical partition keys for multi-tenant workloads:</strong> you can use up to three levels (e.g. TenantId, UserId, id), and every level should have high cardinality. Ending the key with a unique value such as /id lets the earlier levels grow past 20 GB.</li>
<li><strong>Fix hot partitions with the data model, not more RU/s:</strong> throughput is divided across physical partitions, so raising it does not help a skewed key. Change the key, add a spreading level, or split read and write shapes with change feed.</li>
<li><strong>Prefer point reads and project only what you need:</strong> read by id plus partition key when you can, keep queries inside one partition, and select specific properties instead of <code>SELECT *</code>. Exclude paths you never filter or sort on from the indexing policy to lower write cost.</li>
<li><strong>Measure RequestCharge and handle 429s deliberately:</strong> <a href="https://thecodebuzz.com/logging-best-practices-and-guidelines-software-development/">log the RU charge</a> for each important operation, set the SDK retry options, and alert on throttling and partition skew. A 429 caused by a hot partition needs a key fix, not a bigger RU/s setting.</li>
<li><strong>Treat the account default consistency as the ceiling:</strong> Session is the default, so pick the weakest level your correctness rules allow. A request can only relax that level, never make it stronger. If a critical read (e.g. a banking balance check) needs stronger guarantees, set the account default to that stronger level and relax it per request for the reads that can tolerate it. Confirm these rules on the official consistency-levels page.</li>
<li><strong>Decide the partition key early:</strong> you cannot change it in place on an existing container. A change means creating a new container, copying the data and cutting over, so rehearse that migration on a copy first.</li>
</ul>
<p>That&#8217;s all! Happy coding!</p>
<p>Did this guide solve your Cosmos DB partitioning, RU or consistency issue? Please share your questions or experience in the comments below.</p>
<p>Bookmark this page or share it with your team, so it is handy for your next design review. Subscribe to TheCodeBuzz for more database best-practice guides.</p>
<h2 id="faq">FAQ</h2>
<h3><strong>How do I choose a good partition key in Cosmos DB?</strong></h3>
<p>Choose a key with <strong>high cardinality</strong> that spreads both storage and RU use evenly and appears in your most common query filters. Keep each logical partition well under the 20 GB limit, and avoid keys that send all current writes to one value, such as a purely time-based key. If you need more than one level, a hierarchical key of up to three levels (e.g. TenantId, UserId, id) works well for multi-tenant workloads. Decide early, because the key of an existing container cannot be changed in place.</p>
<h3><strong>What is a hot partition in Cosmos DB and how do I fix it?</strong></h3>
<p>A hot partition is one partition that takes far more RU or storage than the others, so it throttles while the rest of the container sits idle. To detect it, compare normalized RU consumption per partition in Azure Monitor. A few partitions near 100% while the container average stays low points to skew. Fix it with the data model: pick a higher-cardinality or hierarchical key, add a spreading level such as a time bucket, or split read and write shapes. Raising RU/s does not help, because throughput is divided across partitions.</p>
<h3><strong>How do I reduce RU consumption in Cosmos DB?</strong></h3>
<p>Use point reads by id and partition key instead of queries, keep queries inside a single partition, and select only the properties you need instead of <code>SELECT *</code>. Exclude paths you never filter or sort on from the indexing policy, since every indexed path is maintained on each write. Then measure the <code>RequestCharge</code> of each operation, because the same query on the same data always costs the same RUs. Check your own workload rather than relying on generic savings figures.</p>
<h3><strong>How do I fix 429 Request Rate Too Large errors in Cosmos DB?</strong></h3>
<p>First check whether the 429s come from a hot partition. If they do, fix the partition key or data model, because adding RU/s will not solve skew. If load is spread evenly, tune the SDK retry settings (<code>MaxRetryAttemptsOnRateLimitedRequests</code> and <code>MaxRetryWaitTimeOnRateLimitedRequests</code>), which honor the <code>x-ms-retry-after-ms</code> header the server returns. If throttling stays steady after that, raise throughput to match the real workload shape. Workloads that are not latency-sensitive can run with less throughput and rely on rate limiting.</p>
<h3><strong>Which Cosmos DB consistency level should I use, and what is the default?</strong></h3>
<p><strong>Session</strong> is the default level, but it is not the right choice for every workload. Pick the weakest level your correctness rules allow, since stronger levels cost more in latency and availability.</p>
<p>The account default is the strongest level any request can get. A request can only weaken it with a per-request override, never strengthen it. So if even one operation, such as a banking balance check, needs a strong guarantee, the account default must be at least that strong. Then relax the other, less critical reads (e.g. a product-review feed) per request.</p>
<p>Confirm on the official consistency-levels page whether Strong is available with multi-region writes, because that detail comes from a third-party source.</p>
<h2 id="sources">Sources and further reading</h2>
<ul>
<li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/hierarchical-partition-keys" target="_blank" rel="noopener">Hierarchical Partition Keys &#8211; Azure Cosmos DB</a> (Microsoft Learn)</li>
<li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/hierarchical-partition-keys-unlimited-scale" target="_blank" rel="noopener">Unlimited logical partition storage with hierarchical partition keys &#8211; Azure Cosmos DB</a> (Microsoft Learn)</li>
<li><a href="https://learn.microsoft.com/en-us/azure/cosmos-db/optimize-cost-reads-writes" target="_blank" rel="noopener">Optimize Request Cost &#8211; Azure Cosmos DB</a> (Microsoft Learn)</li>
</ul>
<p>&nbsp;</p><p>The post <a href="https://thecodebuzz.com/cosmos-db-best-practices-partitioning/">Cosmos DB Best Practices: Partitioning, RU and Consistency</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/cosmos-db-best-practices-partitioning/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Neo4j Best Practices: 18 Rules for Modeling and Cypher</title>
		<link>https://thecodebuzz.com/neo4j-best-practices-graph-modeling-cypher/</link>
					<comments>https://thecodebuzz.com/neo4j-best-practices-graph-modeling-cypher/#respond</comments>
		
		<dc:creator><![CDATA[Izzy]]></dc:creator>
		<pubDate>Tue, 10 Nov 2026 04:45:19 +0000</pubDate>
				<category><![CDATA[Database Best Practices]]></category>
		<category><![CDATA[Cypher]]></category>
		<category><![CDATA[Data Modeling]]></category>
		<category><![CDATA[Graph Database]]></category>
		<category><![CDATA[Neo4j]]></category>
		<category><![CDATA[Performance Tuning]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=31064</guid>

					<description><![CDATA[<p>Neo4j best practices in 18 rules: graph modeling, constraints, indexes, Cypher query tuning and operations, with real PROFILE db hits before and after.</p>
<p>The post <a href="https://thecodebuzz.com/neo4j-best-practices-graph-modeling-cypher/">Neo4j Best Practices: 18 Rules for Modeling and Cypher</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph">You are probably here because a Neo4j query is slow, memory is tight, or you want a graph model that will not hurt later. <strong>Neo4j best practices</strong> come down to modeling for your queries, putting a constraint or index behind every lookup key, reading plans with PROFILE, writing in batches, sizing memory on purpose and testing backups. Below are 18 practices, each with what to do, why and how to check it.</p>



<p class="wp-block-paragraph">Two practices come with real measurements, run on Neo4j 2026.10.2 Community Edition with 50,000 Customer nodes and 100,000 Order nodes. Anything I did not run is marked <strong>not run</strong>. Versions checked on the Neo4j release page on 26 November 2026: 2026.10.2 (current calendar release) and 5.26.34 (5.26 LTS). Cypher examples target Cypher 25, the default in 2026.10.2, and the syntax shown also runs under Cypher 5 unless noted.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/neo4jbp-db-hits-1.png" alt="Bar chart of PROFILE db hits before and after a uniqueness constraint: 100,004 down to 4 for a customer lookup by email, 200,004 down to 2 for a MERGE"/></figure>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#neo4j-best-practices-at-a-glance">Neo4j best practices at a glance</a></li><li><a href="#neo4j-graph-data-modeling-nodes-relationships-properties-and">Neo4j graph data modeling: nodes, relationships, properties and supernodes</a></li><li><a href="#neo4j-indexes-constraints-and-cypher-query-optimization-with">Neo4j constraints and indexes: uniqueness, existence, range, text, fulltext and vector</a></li><li><a href="#batching-writes-and-choosing-between-cypher-25-and-cypher-5">Neo4j query tuning: parameters, PROFILE, MERGE, batching and Cypher versions</a></li><li><a href="#neo4j-performance-tuning-and-operations-memory-monitoring-ba">Neo4j performance tuning and operations: memory, monitoring, backups and upgrades</a></li><li><a href="#common-anti-patterns-and-production-readiness-checklist">Common Neo4j anti-patterns and a production readiness checklist</a></li><li><a href="#key-takeaways">Key takeaways</a></li><li><a href="#faq">Neo4j best practices FAQ</a></li><li><a href="#sources">Sources and further reading</a></li></ul></div>



<h2 class="wp-block-heading" id="neo4j-best-practices-at-a-glance">Neo4j best practices at a glance</h2>



<p class="wp-block-paragraph">Neo4j is a graph database that stores nodes and relationships and is queried with Cypher. If your workload is mostly flat aggregations over tables with few relationships, a relational database is simpler, so check that a graph fits before tuning it. Find your symptom below, then jump to the practice.</p>



<ul class="wp-block-list">
<li><strong>Slow lookups or MERGE:</strong> uniqueness constraint and the right index (practices 4, 5, 9).</li>

<li><strong>Queries that slow down as data grows:</strong> avoid supernodes, name labels and relationship types, cap variable-length paths (practices 2, 3, 11).</li>

<li><strong>High memory or never-ending queries:</strong> avoid cartesian products, Eager and huge <code>collect()</code>, and set memory and transaction limits (practices 8, 13, 14).</li>

<li><strong>Slow imports:</strong> batch with <code>CALL ... IN TRANSACTIONS</code> (practice 10).</li>

<li><strong>Operations:</strong> slow query log, security, backups, pinned versions (practices 15 to 18).</li>
</ul>



<p class="wp-block-paragraph">Neo4j ships calendar-versioned releases and keeps the 5.26 LTS line patched, so check the deployment center for the latest patch before you install.</p>



<h2 class="wp-block-heading" id="neo4j-graph-data-modeling-nodes-relationships-properties-and">Neo4j graph data modeling: nodes, relationships, properties and supernodes</h2>



<p class="wp-block-paragraph">Modeling decides how much work every query does. The fundamentals match <a href="https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/">data modelling for SQL and NoSQL</a>, with one graph twist: connections are stored, so traversing them is cheap unless one node holds too many.</p>



<h3 class="wp-block-heading">1. Model for your queries, and choose node, relationship or property on purpose</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> List your five most important questions before drawing the model, load a sample of real data and run them. Make entities you look up or connect to into nodes, verbs between two entities into relationships, and values you read after reaching a node into properties. Use an intermediate node when a connection carries rich data or joins more than two things, for example a <code>Purchase</code> node linking Customer, Product and Store. For date-range queries, a date or bucket node can beat testing a date property on many nodes; see <a href="https://thecodebuzz.com/neo4j-graph-db-date-range-query-examples/">Neo4j date range query examples</a>.</li>

<li><strong>Why:</strong> Entities and links that appear in the key queries become nodes and relationships, so the plan starts at a small set of nodes and walks outward. Properties add no hops, and a relationship cannot join three entities or be indexed like a node.</li>

<li><strong>How to check:</strong> Run <code>PROFILE</code> on each key query against the sample. If the leaf operators are not index seeks, or db hits are far above the rows returned, or a <code>Filter</code> tests properties on many rows, change the model before loading everything.</li>
</ul>



<h3 class="wp-block-heading">2. Use specific labels and relationship types, with a sensible direction</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Give each kind of entity its own label (<code>Customer</code>, <code>Order</code>) and avoid a catch-all <code>:Node</code> with a <code>type</code> property. Name relationships after the verb (<code>PLACED</code>, <code>CONTAINS</code>) and name the type in every pattern. Each relationship is stored with one direction, so choose the one that reads naturally; you can still traverse it either way by omitting the arrowhead.</li>

<li><strong>Why:</strong> Indexes and constraints are defined per label and property, and the planner uses label counts to choose where to start. A named type lets the expansion follow only the relationships you need, instead of a generic <code>CONNECTED_TO</code> that forces property filters afterwards.</li>

<li><strong>How to check:</strong> <code>CALL db.labels()</code> and <code>CALL db.relationshipTypes()</code> list what you have, and <code>MATCH (n:Label) RETURN count(n)</code> shows how big each label is. In PROFILE, compare db hits on the <code>Expand</code> operator with and without the type.</li>
</ul>



<h3 class="wp-block-heading">3. Avoid supernodes (dense nodes)</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> If a node can collect millions of relationships, split it: by relationship type, by time bucket (<code>Account</code> to <code>Month</code> to <code>Transaction</code>), or with category nodes between the hub and its neighbors. Constraints first, then data:</li>

<li><strong>Why:</strong> A query that goes through a hub must expand every relationship it holds unless you narrow by type and direction. With buckets, it expands only the month it needs.</li>

<li><strong>How to check:</strong> Find the largest nodes with <code>MATCH (n) RETURN n, COUNT { (n)--() } AS degree ORDER BY degree DESC LIMIT 10</code> (scans every node, so run it on a copy or off-peak), and PROFILE the traversal. This bucket model was run on 2026.10.2 with one sample account, and the create and query statements executed correctly.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE CONSTRAINT account_id_unique IF NOT EXISTS
FOR (a:Account) REQUIRE a.accountId IS UNIQUE;
CREATE CONSTRAINT month_key_unique IF NOT EXISTS
FOR (m:Month) REQUIRE (m.accountId, m.month) IS UNIQUE;
CREATE CONSTRAINT transaction_id_unique IF NOT EXISTS
FOR (t:Transaction) REQUIRE t.txId IS UNIQUE;

// Create: account, monthly bucket and transaction
MERGE (a:Account {accountId: $accountId})
MERGE (m:Month {accountId: $accountId, month: $month})
MERGE (a)-&#x5B;:HAS_MONTH]-&gt;(m)
CREATE (m)-&#x5B;:CONTAINS]-&gt;(:Transaction {txId: $txId, amount: $amount, postedAt: datetime($postedAt)});

// Query: one month of transactions for one account
MATCH (:Account {accountId: $accountId})-&#x5B;:HAS_MONTH]-&gt;(:Month {month: $month})-&#x5B;:CONTAINS]-&gt;(t:Transaction)
RETURN t.txId, t.amount, t.postedAt
ORDER BY t.postedAt;
</pre></div>


<h2 class="wp-block-heading" id="neo4j-indexes-constraints-and-cypher-query-optimization-with">Neo4j constraints and indexes: uniqueness, existence, range, text, fulltext and vector</h2>



<p class="wp-block-paragraph">The fastest Cypher queries start at specific nodes found through an index or constraint. A constraint is a rule the database enforces, and a uniqueness constraint also creates a backing range index on its key, so one statement gives you safety and speed.</p>



<h3 class="wp-block-heading">4. Create uniqueness constraints on lookup keys (and existence constraints where you need them)</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Put a uniqueness constraint on the key you look nodes up by, before loading data. <code>IF NOT EXISTS</code> makes the statement safe in deployment scripts. Where data must always be present, add <code>REQUIRE c.name IS NOT NULL</code> or <code>REQUIRE (m.accountId, m.month) IS NODE KEY</code>.</li>

<li><strong>Why:</strong> The planner can start from <code>NodeUniqueIndexSeek</code>, which goes straight to the node, instead of reading every node with the label and testing the property. Existence and node key constraints reject bad writes at the source. Those two types are Enterprise Edition features: Community Edition on 2026.10.2 rejected both statements with a not supported in this edition error, so they are <strong>not run</strong> to success here.</li>

<li><strong>How to check:</strong> <code>SHOW CONSTRAINTS</code> lists them, and PROFILE shows the effect. Measured on 2026.10.2 with 50,000 customers, <code>MATCH (c:Customer {email: 'user42423@example.com'}) RETURN c</code> before and after the constraint: db hits went from <strong>100,004</strong> (NodeByLabelScan, then Filter on email) to <strong>4</strong> (NodeUniqueIndexSeek). A duplicate email is now rejected with a clear error: <code>Property uniqueness constraint violated: Node(42423) already exists with label Customer and property email</code>.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
PROFILE
MATCH (c:Customer {email: $email})-&#x5B;:PLACED]-&gt;(o:Order)
RETURN o.orderId, o.total;

CREATE CONSTRAINT customer_email_unique IF NOT EXISTS
FOR (c:Customer) REQUIRE c.email IS UNIQUE;

CREATE CONSTRAINT customer_name_required IF NOT EXISTS
FOR (c:Customer) REQUIRE c.name IS NOT NULL;  -- Enterprise only
</pre></div>


<h3 class="wp-block-heading">5. Pick the right index type, and confirm it is used</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Use a <strong>range</strong> index (the default <code>CREATE INDEX</code>) for equality, ranges and <code>STARTS WITH</code>; a <strong>text</strong> index for <code>CONTAINS</code> and <code>ENDS WITH</code>; a <strong>point</strong> index for spatial distance; a <strong>full-text</strong> index for word search with scoring; a <strong>vector</strong> index for similarity search on embeddings. When queries always filter on the same properties together, use one composite index such as <code>(o.customerId, o.total)</code>, with the equality property first. Drop indexes that no query uses.</li>

<li><strong>Why:</strong> Each type stores data the way its predicate reads it, so the planner can answer with a seek instead of a scan. An index costs disk, memory and write time, and earns it only when plans use it.</li>

<li><strong>How to check:</strong> <code>SHOW INDEXES YIELD name, type, state</code> must show <code>ONLINE</code>, and PROFILE should show <code>NodeIndexSeek</code> rather than <code>NodeByLabelScan</code>. I ran the range, text, point, full-text and vector creation statements and a range <code>STARTS WITH</code> query on 2026.10.2 (the plan used <code>NodeUniqueIndexSeekByRange</code>, 12 db hits), and a full-text query returned a result set. The point and vector indexes were created but <strong>not queried</strong>. The composite index statement ran, but its benefit was <strong>not measured</strong>.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE INDEX order_date_range IF NOT EXISTS FOR (o:Order) ON (o.orderDate);
CREATE TEXT INDEX product_name_text IF NOT EXISTS FOR (p:Product) ON (p.name);
CREATE POINT INDEX store_location IF NOT EXISTS FOR (s:Store) ON (s.location);
CREATE FULLTEXT INDEX product_ft IF NOT EXISTS FOR (p:Product) ON EACH &#x5B;p.name, p.description];
CREATE VECTOR INDEX doc_embedding IF NOT EXISTS FOR (d:Doc) ON d.embedding
OPTIONS {indexConfig: {`vector.dimensions`: 1536, `vector.similarity_function`: &#039;cosine&#039;}};
CREATE INDEX order_cust_total IF NOT EXISTS FOR (o:Order) ON (o.customerId, o.total);
</pre></div>


<h2 class="wp-block-heading" id="batching-writes-and-choosing-between-cypher-25-and-cypher-5">Neo4j query tuning: parameters, PROFILE, MERGE, batching and Cypher versions</h2>



<p class="wp-block-paragraph">Once the data is modeled and indexed, most remaining tuning is about the shape of the query. Read plans from the bottom up. <strong>Db hits</strong> are units of storage work, and a gap between estimated and actual rows means the planner chose on wrong numbers.</p>



<h3 class="wp-block-heading">6. Use parameters instead of literals</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Pass values as <code>$email</code>, never by building the query string, and send them as parameters from your driver.</li>

<li><strong>Why:</strong> The planner can reuse a cached plan across values, and values never become part of the query text, which also prevents Cypher injection. Neo4j can auto-parameterize some simple literals (you saw <code>$autostring_0</code> in plans), but explicit parameters are the reliable way.</li>

<li><strong>How to check:</strong> The query log or <code>SHOW TRANSACTIONS</code> shows the same query text with different values when parameters work. The Cypher parameter form was run in the examples here; driver code was <strong>not run</strong>.</li>
</ul>



<h3 class="wp-block-heading">7. Read plans with EXPLAIN and PROFILE, and filter, limit and project early</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Use <code>EXPLAIN</code> to see the plan without running the query and <code>PROFILE</code> to run it and see rows and db hits per operator. Start at the leaf operators, then the biggest db hits. Put the most selective match first, <code>LIMIT</code> as soon as ordering allows, and return only the properties you need instead of whole nodes.</li>

<li><strong>Why:</strong> The plan shows which access path was chosen: <code>NodeIndexSeek</code> and <code>NodeUniqueIndexSeek</code> start at specific nodes, <code>NodeByLabelScan</code> reads every node with the label. Every operator after a filter handles fewer rows, and fewer bytes cross the network.</li>

<li><strong>How to check:</strong> Warning signs are NodeByLabelScan on a large label, CartesianProduct, Eager and estimated rows far from actual rows. The <code>Rows</code> column should fall as you move up the plan. Use PROFILE while tuning, not on every production query, because it adds overhead.</li>
</ul>



<h3 class="wp-block-heading">8. Avoid cartesian products, Eager operators and huge collect() lists</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Connect patterns in one <code>MATCH</code> with a shared variable, or split unrelated work into separate steps. Where a write and a read touch the same property, restructure or batch so the planner does not need <code>Eager</code>. Use <code>WITH ... count(*)</code> to collapse rows early, and <code>collect()</code> only for lists you know are small.</li>

<li><strong>Why:</strong> <code>CartesianProduct</code> combines every left row with every right row, so two lists of 1,000 rows give 1,000,000. <code>Eager</code> loads all incoming rows into memory before passing any on. <code>collect()</code> holds the whole list on the heap.</li>

<li><strong>How to check:</strong> PROFILE and look for <code>CartesianProduct</code> and <code>Eager</code>, check the row counts on their children, and sort by <code>Memory (Bytes)</code>. When I ran a two-pattern query where each side was a single-row index seek, a CartesianProduct appeared with only 6 db hits, so it is harmless only when both sides are tiny. The Eager example in the Neo4j operator reference is <strong>not run</strong> by me.</li>
</ul>



<h3 class="wp-block-heading">9. Write idempotent MERGE on a constrained key</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> <code>MERGE</code> on the constrained key only, then set other properties with <code>ON CREATE SET</code> and <code>ON MATCH SET</code>. Do not merge on a whole pattern with many properties.</li>

<li><strong>Why:</strong> With the constraint the lookup is an index seek (<code>MergeUniqueNode</code>) and two concurrent writers cannot both create the node. Without it, MERGE has to find the node by scanning the label.</li>

<li><strong>How to check:</strong> PROFILE the MERGE and look for <code>MergeUniqueNode</code>. Measured on 2026.10.2 with 100,000 orders: <code>MERGE (o:Order {orderId: 424242})</code> cost <strong>200,004</strong> db hits (NodeByLabelScan plus Filter) before the constraint and <strong>2</strong> db hits (MergeUniqueNode) after it.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE CONSTRAINT order_id_unique IF NOT EXISTS
FOR (o:Order) REQUIRE o.orderId IS UNIQUE;

MERGE (o:Order {orderId: $orderId})
ON CREATE SET o.total = $total, o.createdAt = datetime()
ON MATCH SET o.total = $total
RETURN o.orderId;
</pre></div>


<h3 class="wp-block-heading">10. Batch writes with CALL IN TRANSACTIONS</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> For big loads, create the constraint first, then send rows with <code>UNWIND $rows</code> or <code>LOAD CSV</code> and commit every few thousand rows with <code>CALL (row) { ... } IN TRANSACTIONS OF 10000 ROWS</code>. This must run in an implicit transaction, so in Neo4j Browser prefix it with <code>:auto</code>. For files, see <a href="https://thecodebuzz.com/neo4j-how-to-read-csv-file/">how to read a CSV file in Neo4j</a>.</li>

<li><strong>Why:</strong> Each batch is its own small transaction, so memory and locks stay bounded and a failure only affects the current batch. Batches already committed stay committed.</li>

<li><strong>How to check:</strong> Count the result afterwards and watch heap while the load runs. I ran this form on 2026.10.2 with a parameter list of two rows (batch size 1) and 30,000 <code>MERGE</code> rows in batches of 10,000. <code>IN CONCURRENT TRANSACTIONS</code> and <code>DISJOINT BY</code> (Cypher 25, introduced in 2026.06) were <strong>not run</strong>. Concurrent batches can deadlock when two touch the same node, so test them on your data first.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
UNWIND $rows AS row
CALL (row) {
  MERGE (o:Order {orderId: row.orderId})
  SET o.total = row.total
} IN TRANSACTIONS OF 10000 ROWS;
</pre></div>


<h3 class="wp-block-heading">11. Cap variable-length paths</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Write <code>[:KNOWS*1..4]</code>, not <code>[:KNOWS*]</code>, and anchor the start node on an indexed property.</li>

<li><strong>Why:</strong> An unbounded path can explore most of the graph from the start node, which causes memory spikes and queries that never finish.</li>

<li><strong>How to check:</strong> PROFILE a capped query and compare the rows at the <code>VarLengthExpand</code> operator when you raise the upper bound. I ran a <code>*1..3</code> query on the sample data; timing impact at scale is <strong>not measured</strong>.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
MATCH p = (c:Customer {customerId: $id})-&#x5B;:PLACED*1..3]-(x)
RETURN count(p);
</pre></div>


<h3 class="wp-block-heading">12. Choose the Cypher version deliberately</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Cypher 5 is frozen apart from fixes; Cypher 25 gains features with each server release. Set the default per database and override per query when migrating.</li>

<li><strong>Why:</strong> You decide when syntax and planner changes arrive instead of inheriting them. The Neo4j docs say databases created on 2026.02 or later set <code>db.query.default_language=CYPHER_25</code> explicitly in <code>neo4j.conf</code> (the 2026.10.2 file I installed has it), while existing databases keep their file, so check the value before you copy a config between servers.</li>

<li><strong>How to check:</strong> <code>CALL dbms.components()</code> lists the supported Cypher versions (on 2026.10.2: 5 and 25), and the version appears in PROFILE output. The <code>ALTER DATABASE</code> statement is <strong>not run</strong> by me.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
ALTER DATABASE sales SET DEFAULT LANGUAGE CYPHER 25;

CYPHER 5
MATCH (c:Customer {customerId: $id}) RETURN c.name;
</pre></div>


<h2 class="wp-block-heading" id="neo4j-performance-tuning-and-operations-memory-monitoring-ba">Neo4j performance tuning and operations: memory, monitoring, backups and upgrades</h2>



<p class="wp-block-paragraph">Memory has two main areas. The <strong>page cache</strong> holds graph data and indexes. The <strong>heap</strong> holds query execution state. A larger page cache does not fix a query that builds huge intermediate results, so fix the query first.</p>



<h3 class="wp-block-heading">13. Size the page cache and heap with the memory recommendation</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Run the command with your machine&#8217;s memory and put the result in <code>neo4j.conf</code>. Set initial and maximum heap to the same value, and keep the heap under about 31 GB, because compressed object pointers are lost above that.</li>

<li><strong>Why:</strong> Hot data stays in memory so reads avoid disk, and the heap is large enough for query state. The tool leaves room for the operating system and native memory used by Lucene and Netty.</li>

<li><strong>How to check:</strong> <code>bin/neo4j-admin server memory-recommendation</code>. On a 16 GiB machine it printed a heap of about 5g and a page cache of about 7g, leaving about 4g for the operating system. Compare with the real size of your store and indexes, and watch the page cache hit ratio over time.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code ">
server.memory.heap.initial_size=5g
server.memory.heap.max_size=5g
server.memory.pagecache.size=7g
</div>


<h3 class="wp-block-heading">14. Cap transaction memory and time, and leave checkpoints at the default</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Log GC activity and set limits so one query cannot take the server: <code>db.memory.transaction.total.max</code> for all transactions in a database, and <code>db.transaction.timeout</code> for the maximum duration. Leave the checkpoint policy at the default <code>PERIODIC</code> (<code>db.checkpoint.interval.tx</code>, default 100000) unless you have measured a reason to change it.</li>

<li><strong>Why:</strong> Limits turn a runaway query into one failed transaction instead of a slow or crashed server. A checkpoint flushes page cache changes to the store files, which bounds how much transaction log must be replayed after a crash.</li>

<li><strong>How to check:</strong> Metrics for heap and GC, <code>SHOW TRANSACTIONS</code> for long-running work, and <code>debug.log</code> for checkpoint entries. I did not run load tests, so recommended values are <strong>not benchmarked</strong> and checkpoint changes were <strong>not tested</strong>.</li>
</ul>



<h3 class="wp-block-heading">15. Log slow queries and monitor the basics</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Turn on the query log at <code>INFO</code> with a threshold. Do not use <code>VERBOSE</code> for this: it logs the start and end of all queries.</li>

<li><strong>Why:</strong> At <code>INFO</code> the threshold decides which queries are written, so only slow ones appear, and they show which statements to PROFILE first.</li>

<li><strong>How to check:</strong> Read <code>query.log</code> and sort by elapsed time. Also track page cache hit ratio, heap and GC, and open, committed and rolled-back transactions.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code ">
db.logs.query.enabled=INFO
db.logs.query.threshold=1s
</div>


<h3 class="wp-block-heading">16. Apply security basics</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Give each application a least-privilege user and role, encrypt Bolt and HTTP traffic with TLS, and always use parameters. Role-based access control is an Enterprise Edition feature, and the statements below are <strong>not run</strong> here.</li>

<li><strong>Why:</strong> An application that can only read cannot change data or schema if its credentials leak.</li>

<li><strong>How to check:</strong> <code>SHOW USERS</code> and <code>SHOW ROLE app_reader PRIVILEGES</code> in an Enterprise setup, and a test that a read-only user cannot write.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE ROLE app_reader IF NOT EXISTS;
GRANT ACCESS ON DATABASE neo4j TO app_reader;
GRANT MATCH {*} ON GRAPH neo4j TO app_reader;
CREATE USER report_svc IF NOT EXISTS SET PASSWORD $password CHANGE NOT REQUIRED;
GRANT ROLE app_reader TO report_svc;
</pre></div>


<h3 class="wp-block-heading">17. Back up regularly, test restores, and do not treat a cluster as a backup</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Take scheduled backups, store them away from the database host and restore them into a separate environment. In Enterprise, <code>--type=AUTO</code> lets Neo4j choose between a full and a differential backup. Run a cluster when you need availability and read scaling, route reads with <code>RoutingControl.READ</code> in the driver, and keep backups as well.</li>

<li><strong>Why:</strong> A restore test is the only proof that the backup is complete and that your runbook works. A cluster serves reads from several members and survives a server outage, but it copies mistakes, such as a bad delete, to the other members.</li>

<li><strong>How to check:</strong> Restore into staging on a schedule, run <code>SHOW DATABASES</code> and a few counts, and record the restore time. The backup command and cluster behavior are <strong>not run</strong> here, because online backup and clustering are Enterprise features.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
neo4j-admin database backup --from=db-host:6362 --type=AUTO --to-path=/backups/neo4j neo4j
</pre></div>


<h3 class="wp-block-heading">18. Pin versions and test upgrades</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Pin exact patch versions, read the release notes, and rehearse every upgrade in staging. Choose the 5.26 LTS line for few changes, or the calendar series for new features earlier. For clusters, follow the documented rolling-upgrade order one member at a time.</li>

<li><strong>Why:</strong> Calendar releases arrive often, so each one is a change to test, and patch releases carry fixes.</li>

<li><strong>How to check:</strong> <code>CALL dbms.components()</code> prints the running version (2026.10.2 here), and the deployment center lists the latest patch (5.26.34 and 2026.10.2 on 26 November 2026). Upgrade steps were <strong>not run</strong> here.</li>
</ul>



<h2 class="wp-block-heading" id="common-anti-patterns-and-production-readiness-checklist">Common Neo4j anti-patterns and a production readiness checklist</h2>



<p class="wp-block-paragraph">Most production problems come from a short list of mistakes, each fixed by a practice above.</p>



<figure class="wp-block-table"><table><thead><tr><th>Anti-pattern</th><th>Symptom</th><th>Practice</th></tr></thead><tbody><tr><td>Generic relationship type or label</td><td>Property filters to tell edges apart, label scans</td><td>2</td></tr><tr><td>Supernode hub</td><td>Traversal slows as one node grows</td><td>3</td></tr><tr><td>No constraint on the MERGE key</td><td>Label scans inside MERGE, duplicates</td><td>4, 9</td></tr><tr><td>Literals instead of parameters</td><td>Plans not reused, injection risk</td><td>6</td></tr><tr><td>Cartesian product or Eager in the plan</td><td>Row counts explode, memory spikes</td><td>8</td></tr><tr><td>Unbounded variable-length path</td><td>Queries that never finish</td><td>11</td></tr><tr><td>One giant import transaction</td><td>Heap pressure, long rollbacks</td><td>10</td></tr><tr><td>Untested upgrade or restore</td><td>Surprises during an incident</td><td>17, 18</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>Before going live:</strong> run the key queries on a loaded sample, confirm constraints and indexes with PROFILE, use parameters, cap every <code>*</code> path, batch imports, size memory, turn on the query log, schedule backups and rehearse a restore, review roles and TLS, and pin the version. The same query-first thinking applies to <a href="https://thecodebuzz.com/cassandra-best-practices-guidelines/">Cassandra data modeling</a> and <a href="https://thecodebuzz.com/redis-cache-best-practices-development/">Redis caching</a>. A graph is often the wrong choice for bulk analytics scans or data with few relationships.</p>



<h2 class="wp-block-heading" id="key-takeaways">Key takeaways</h2>



<ul class="wp-block-list">
<li><strong>Model for queries:</strong> specific labels and relationship types, intermediate nodes for rich links, buckets for dense hubs.</li>

<li><strong>Constraint first:</strong> a uniqueness constraint turned 100,004 db hits into 4 on a customer lookup and 200,004 into 2 on a MERGE in my test.</li>

<li><strong>Read PROFILE:</strong> NodeByLabelScan, CartesianProduct, Eager and estimate gaps are the warning signs.</li>

<li><strong>Batch and cap:</strong> CALL IN TRANSACTIONS for writes, upper bounds on variable-length paths.</li>

<li><strong>Operate on purpose:</strong> size memory with the recommendation tool, log slow queries, test restores, pin versions.</li>
</ul>



<p class="wp-block-paragraph">Not run in this guide: Enterprise-only constraints, roles, backup and cluster statements, concurrent batches, point and vector queries, driver code and the Cypher version switch. Test them on your own version before relying on them. Results on other data sizes or editions will differ.</p>



<div class="wp-block-group has-background" style="border-radius:8px;background-color:#b6d9ac;padding-top:20px;padding-right:24px;padding-bottom:20px;padding-left:24px"><div class="wp-block-group__inner-container is-layout-constrained wp-container-core-group-is-layout-0d2d72cd wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph" style="font-size:20px"><strong>Found this useful?</strong></p>



<p class="wp-block-paragraph">Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.</p>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noopener">Subscribe to TheCodeBuzz</a></div>
</div>
</div></div>



<h2 class="wp-block-heading" id="faq">Neo4j best practices FAQ</h2>



<h3 class="wp-block-heading">What are the best practices for Neo4j?</h3>



<p class="wp-block-paragraph">Model for your key queries, use specific labels and relationship types, add a uniqueness constraint on every lookup key, pass parameters, read plans with PROFILE, batch writes with CALL IN TRANSACTIONS, cap variable-length paths, size the page cache and heap, log slow queries, and test backups and restores.</p>



<h3 class="wp-block-heading">How do I tune a slow Neo4j query?</h3>



<p class="wp-block-paragraph">Run PROFILE and look at the leaf operators. Replace NodeByLabelScan with an index seek by adding an index or constraint, connect patterns that form a CartesianProduct, filter and limit early, return only needed properties, and cap variable-length paths. In a measured test here, one constraint cut a lookup from 100,004 db hits to 4.</p>



<h3 class="wp-block-heading">Which constraints and indexes does Neo4j support?</h3>



<p class="wp-block-paragraph">Uniqueness constraints in Community Edition, plus existence and node key constraints in Enterprise Edition. Index types are range, text, point, full-text and vector, and composite indexes cover several properties. Check them with SHOW INDEXES and SHOW CONSTRAINTS.</p>



<h2 class="wp-block-heading" id="sources">Sources and further reading</h2>



<ul class="wp-block-list">
<li><a href="https://neo4j.com/docs/cypher-manual/current/planning-and-tuning/query-tuning/" target="_blank" rel="noopener">Query tuning, Cypher Manual</a></li>

<li><a href="https://neo4j.com/docs/cypher-manual/current/constraints/managing-constraints/" target="_blank" rel="noopener">Managing constraints, Cypher Manual</a></li>

<li><a href="https://neo4j.com/docs/cypher-manual/current/subqueries/subqueries-in-transactions/" target="_blank" rel="noopener">Subqueries in transactions, Cypher Manual</a></li>

<li><a href="https://neo4j.com/docs/operations-manual/current/performance/memory-configuration/" target="_blank" rel="noopener">Memory configuration, Operations Manual</a></li>
</ul>



<script type="application/ld+json">{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "What are the best practices for Neo4j?", "acceptedAnswer": {"@type": "Answer", "text": "Model for your key queries, use specific labels and relationship types, add a uniqueness constraint on every lookup key, pass parameters, read plans with PROFILE, batch writes with CALL IN TRANSACTIONS, cap variable-length paths, size the page cache and heap, log slow queries, and test backups and restores."}}, {"@type": "Question", "name": "How do I tune a slow Neo4j query?", "acceptedAnswer": {"@type": "Answer", "text": "Run PROFILE and look at the leaf operators. Replace NodeByLabelScan with an index seek by adding an index or constraint, connect patterns that form a CartesianProduct, filter and limit early, return only needed properties, and cap variable-length paths. In a measured test here, one constraint cut a lookup from 100,004 db hits to 4."}}, {"@type": "Question", "name": "Which constraints and indexes does Neo4j support?", "acceptedAnswer": {"@type": "Answer", "text": "Uniqueness constraints in Community Edition, plus existence and node key constraints in Enterprise Edition. Index types are range, text, point, full-text and vector, and composite indexes cover several properties. Check them with SHOW INDEXES and SHOW CONSTRAINTS."}}]}</script><p>The post <a href="https://thecodebuzz.com/neo4j-best-practices-graph-modeling-cypher/">Neo4j Best Practices: 18 Rules for Modeling and Cypher</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/neo4j-best-practices-graph-modeling-cypher/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>DynamoDB Best Practices: Single-Table Design, Keys and Cost</title>
		<link>https://thecodebuzz.com/dynamodb-best-practices-single-table-design/</link>
					<comments>https://thecodebuzz.com/dynamodb-best-practices-single-table-design/#respond</comments>
		
		<dc:creator><![CDATA[Izzy]]></dc:creator>
		<pubDate>Sat, 31 Oct 2026 03:36:42 +0000</pubDate>
				<category><![CDATA[Database Best Practices]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[Cost Optimization]]></category>
		<category><![CDATA[Data Modeling]]></category>
		<category><![CDATA[DynamoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=30969</guid>

					<description><![CDATA[<p>DynamoDB best practices for single-table design, partition key choice, hot partitions, GSIs and cost, with Python and C# examples and a checklist.</p>
<p>The post <a href="https://thecodebuzz.com/dynamodb-best-practices-single-table-design/">DynamoDB Best Practices: Single-Table Design, Keys and Cost</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>Today in this article, we will see DynamoDB best practices for modeling data, choosing keys, avoiding hot partitions and controlling the bill. The guide is for engineers, architects and DBAs who run DynamoDB in production, or who are about to. It covers data modeling and single-table design, partition and sort keys, GSIs, transactions and replication, cost, and operations, followed by a common anti-patterns table and a production readiness checklist.</p>
<p>Amazon DynamoDB is a managed key-value and document database. It has no versions and no maintenance windows, so new features ship continuously, and the notes in this guide reflect AWS announcements up to October 2026. The approach is access-pattern-first: you list how the application reads and writes data, then shape the keys and indexes around that list. Single-table design is explained as a tool for the right cases, not a universal rule.</p>
<p>Before we start, please check the prerequisites: basic familiarity with tables, items, partition key and sort key, plus an AWS account and a current SDK (boto3 for Python or the AWS SDK for .NET).</p>
<blockquote><p><strong>Version note:</strong> This guide targets the current DynamoDB service as of October 2026, including vector search (generally available Aug 5, 2026), global tables with multi-Region strong consistency (15 AWS Regions as of the Sept 2026 expansion) and the Streams AT_TIMESTAMP shard iterator (announced Oct 15, 2026).</p></blockquote>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><strong>In this guide</strong></p>
<ul>
<li><a href="#dynamodb-best-practices-at-a-glance">DynamoDB Best Practices at a Glance</a></li>
<li><a href="#dynamodb-data-modeling-access-patterns-and-single-table-desi">DynamoDB Data Modeling: Access Patterns and Single-Table Design</a></li>
<li><a href="#partition-key-sort-key-and-gsi-design-avoid-hot-partitions">Partition Key, Sort Key and GSI Design: Avoid Hot Partitions</a></li>
<li><a href="#transactions-consistency-replication-and-streams">Transactions, Consistency, Replication and Streams</a></li>
<li><a href="#dynamodb-cost-optimization-on-demand-vs-provisioned-and-item">DynamoDB Cost Optimization: On-Demand vs Provisioned and Item Size</a></li>
<li><a href="#dynamodb-security-backups-monitoring-anti-patterns-and-produ">DynamoDB Security, Backups, Monitoring, Anti-Patterns and Production Checklist</a></li>
<li><a href="#key-takeaways">Key takeaways</a></li>
<li><a href="#faq">FAQ</a></li>
</ul>
<h2></h2>
<h2 id="dynamodb-best-practices-at-a-glance">DynamoDB Best Practices at a Glance</h2>
<p>Today in this guide, we will see how to design, run and pay for Amazon DynamoDB in production. DynamoDB is a fully managed NoSQL key-value and document database from AWS. We will cover data modeling, key design, indexes, transactions, replication, cost, security, backups and monitoring.</p>
<p><strong>Version note:</strong> DynamoDB has no versions or maintenance windows, because features ship continuously. This guide is current to the Oct 2026 announcements.</p>
<blockquote><p><strong>In plain English:</strong> A partition is a physical storage unit that serves a slice of your table&#8217;s keys. Think of one checkout counter among many in a supermarket: each counter handles only some customers, and one counter can only serve so many people at a time.</p></blockquote>
<p>The table below shows the main rules for each area. Later sections explain the reasoning behind each one.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Area</th>
<th>Do this</th>
<th>Avoid this</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Data modeling</strong></td>
<td>Start from access patterns, then shape the table (DynamoDB single table design where patterns are known and related)</td>
<td>Copying a relational schema and expecting joins</td>
</tr>
<tr>
<td><strong>Partition key</strong></td>
<td>Use a high-cardinality key with even traffic (e.g. orderId)</td>
<td>Timestamp or status as the partition key</td>
</tr>
<tr>
<td><strong>Sort key</strong></td>
<td>Use it for ordering and range queries inside one item collection</td>
<td>Putting unrelated data under one sort key scheme</td>
</tr>
<tr>
<td><strong>GSIs</strong></td>
<td>Add one per proven access pattern, keep it sparse, project only needed attributes</td>
<td>One GSI per query idea</td>
</tr>
<tr>
<td><strong>Query and reads</strong></td>
<td>Use Query, ProjectionExpression and eventually consistent reads where staleness is fine</td>
<td>Scan in hot paths, FilterExpression as an index</td>
</tr>
<tr>
<td><strong>Transactions</strong></td>
<td>Use conditional writes first, transactions only for all-or-nothing needs</td>
<td>Wrapping every write in a transaction</td>
</tr>
<tr>
<td><strong>Replication</strong></td>
<td>Pick global table mode by the consistency you need</td>
<td>Assuming cross-Region reads are always fresh</td>
</tr>
<tr>
<td><strong>Capacity mode</strong></td>
<td>Start with on-demand; move to provisioned only for steady traffic</td>
<td>Leaving over-provisioned capacity unchanged</td>
</tr>
<tr>
<td><strong>Item size and blobs</strong></td>
<td>Keep blobs in S3 and store a reference</td>
<td>Large payloads inline in items</td>
</tr>
<tr>
<td><strong>Security</strong></td>
<td>Least-privilege IAM, encryption, private endpoints</td>
<td>Broad table-wide permissions, secrets in attributes</td>
</tr>
<tr>
<td><strong>Backups</strong></td>
<td>Turn on PITR and deletion protection</td>
<td>Never testing a restore</td>
</tr>
<tr>
<td><strong>Monitoring</strong></td>
<td>Alarm on throttles, use Contributor Insights</td>
<td>Finding hot keys only after users complain</td>
</tr>
</tbody>
</table>
</figure>
<h2 id="dynamodb-data-modeling-access-patterns-and-single-table-desi">DynamoDB Data Modeling: Access Patterns and Single-Table Design</h2>
<p>For <a href="https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/">DynamoDB data modeling</a>, <strong>list your access patterns first</strong> (e.g. &#8220;get customer by ID&#8221;, &#8220;list a customer&#8217;s orders newest first&#8221;) and shape the table to serve them. DynamoDB has no joins, so the table layout has to answer each question with a single key lookup or Query.</p>
<h3>What Is Single-Table Design?</h3>
<p>DynamoDB single table design means you <a href="https://thecodebuzz.com/mongodb-schema-design-guidelines-best-practices/">denormalize and pre-join data</a> at write time. Related items share a partition key, so one Query returns them together. The table shape follows how the data is read, not how it is normalized.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note :</strong> A single-table layout is like filing a customer&#8217;s invoice, address and receipts in one folder. You pull one folder instead of visiting three cabinets. The analogy stops fitting when the folder grows very large, because one key has throughput limits (covered in the next section).</p></blockquote>
<h3>Which Key Conventions Should You Follow?</h3>
<p>Use generic <code>PK</code> and <code>SK</code> attribute names, prefix values with the entity type (e.g. <code>USER#</code>, <code>ORDER#</code>), and add an <code>entityType</code> attribute. The attribute helps when debugging and lets stream consumers route each item to the right handler.</p>
<p>The table below shows a small item collection for a retail customer and orders. One Query on <code>PK = USER#1001</code> returns the profile and all orders. Adding <code>begins_with(SK, "ORDER#")</code> returns only the orders.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>PK</th>
<th>SK</th>
<th>entityType</th>
<th>Attributes</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>USER#1001</strong></td>
<td>PROFILE</td>
<td>User</td>
<td>name, email</td>
</tr>
<tr>
<td><strong>USER#1001</strong></td>
<td>ORDER#2026-10-20#A17</td>
<td>Order</td>
<td>total, status</td>
</tr>
<tr>
<td><strong>USER#1001</strong></td>
<td>ORDER#2026-10-25#A18</td>
<td>Order</td>
<td>total, status</td>
</tr>
</tbody>
</table>
</figure>
<h3>How Do You Model Relationships?</h3>
<p>Model one-to-many with a shared PK and SK prefixes, as in the table above. Model many-to-many with the <strong>adjacency list pattern</strong>, where each relationship is its own item.</p>
<ul>
<li><strong>Education example:</strong> store <code>PK = STUDENT#7</code>, <code>SK = COURSE#MATH101</code> and the mirror item <code>PK = COURSE#MATH101</code>, <code>SK = STUDENT#7</code>. A Query on either side lists the other.</li>
<li><strong>Retail example:</strong> do the same for products and categories. A GSI that swaps the keys can also serve the reverse lookup.</li>
</ul>
<h3>When Should You Not Use a Single Table?</h3>
<p>Avoid a single table when entities scale or fail independently, need separate IAM, backup or blast radius, or have simple or still-changing access patterns. It pays off when patterns are <strong>known, related and high volume</strong>. The animated diagram below walks through this decision step by step.</p>
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/10/dynamodb-best-practices-single-table-design-diagram-2.gif" alt="Decision tree: known stable patterns, co-read high-volume entities and no isolation needs lead to a single table; any other answer leads to separate tables." width="1200" height="675" /><figcaption>Choose a single table only when access patterns are known, related and high volume, and the entities don&#8217;t need isolation.</figcaption></figure>
<p>The table compares the two approaches across the main concerns.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Concern</th>
<th>Single table</th>
<th>Separate tables</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Scaling</strong></td>
<td>Shared table settings</td>
<td>Tuned per entity</td>
</tr>
<tr>
<td><strong>IAM and backup scope</strong></td>
<td>One policy and one backup for everything</td>
<td>Separate policies, backups and blast radius</td>
</tr>
<tr>
<td><strong>Change tolerance</strong></td>
<td>New patterns may need remodeling or backfills</td>
<td>Easier to adapt</td>
</tr>
<tr>
<td><strong>Readability</strong></td>
<td>Harder; needs documented key conventions</td>
<td>Familiar, one entity per table</td>
</tr>
</tbody>
</table>
</figure>
<h3>How Do Vector Search and Large Blobs Affect Modeling?</h3>
<p>Native vector search became generally available on Aug 5, 2026. Embeddings sit next to your other attributes, and a vector index type works alongside GSIs and LSIs. For many RAG and semantic-search cases, this removes the need for a second database. AWS claims single-digit millisecond latency at 99%+ recall, so verify that against your own data.</p>
<p>Keep large blobs (images, PDFs, long documents) in S3 and store only the reference in the item. Item size drives read and write units, so a lean item is cheaper to read and write. The cost section explains the arithmetic.</p>
<h2 id="partition-key-sort-key-and-gsi-design-avoid-hot-partitions">Partition Key, Sort Key and GSI Design: Avoid Hot Partitions</h2>
<p>Choose a <strong>high-cardinality partition key</strong> (many distinct values) whose traffic spreads evenly, and use the sort key for ordering and range queries inside one item collection. AWS advises designing for uniform activity across all partition keys in the table and in its secondary indexes.</p>
<h3>What are the per-partition limits in DynamoDB?</h3>
<p>Each partition is designed to deliver up to <strong>3,000 read units and 1,000 write units per second</strong>. Item size counts toward these limits.</p>
<ul>
<li><strong>Read unit:</strong> one strongly consistent read per second, or two eventually consistent reads per second, for an item up to 4 KB.</li>
<li><strong>Write unit:</strong> one write per second for an item up to 1 KB.</li>
</ul>
<p>Example: a 20 KB item costs 5 read units per strongly consistent read (20 / 4). About 600 reads per second on that single item uses 3,000 read units, which is the partition limit.</p>
<h3>What does adaptive capacity fix, and what does it not?</h3>
<p>Adaptive capacity works in both on-demand and provisioned modes and helps when traffic is uneven across keys. It cannot raise the hard per-partition limit for one hot key. Total throughput is still bounded by your provisioned throughput or the on-demand table limit.</p>
<blockquote><p><strong>In plain English:</strong> A hot partition is one checkout lane with a huge queue while the other lanes sit empty. Adding more lanes does not help if every customer insists on the same lane.</p></blockquote>
<h3>Which partition keys work and which fail?</h3>
<p>The table below compares common choices for DynamoDB partition key design.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Key</th>
<th>Why it works or fails</th>
<th>Fix</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>userId, orderId</strong></td>
<td>Many distinct values, traffic spreads well.</td>
<td>Use as is.</td>
</tr>
<tr>
<td><strong>date, timestamp</strong></td>
<td>All current writes hit today&#8217;s key.</td>
<td>Move time to the sort key.</td>
</tr>
<tr>
<td><strong>status, boolean</strong></td>
<td>Only a few values, so a few partitions take everything.</td>
<td>Use a sparse GSI instead.</td>
</tr>
<tr>
<td><strong>country</strong></td>
<td>Low cardinality, skewed by population.</td>
<td>Combine with another attribute.</td>
</tr>
<tr>
<td><strong>tenantId</strong></td>
<td>Risky when one tenant is far larger than the rest.</td>
<td>Write-shard the large tenant.</td>
</tr>
</tbody>
</table>
</figure>
<h3>How do you design the sort key?</h3>
<p>The sort key orders items inside one partition key and enables range queries. Use ISO 8601 timestamps or prefixed values such as <code>ORDER#2026-10-25</code>, because they sort correctly as strings. Sort keys compare as plain strings, so a longer value sorts after its shorter prefix.</p>
<ul>
<li><strong>begins_with:</strong> fetch all items for one prefix, e.g. <code>ORDER#2026-10</code> for a month.</li>
<li><strong>between:</strong> fetch a date range. Both bounds are inclusive, so choose the upper bound with care (see the pitfall below).</li>
<li><strong>Composite sort keys:</strong> encode hierarchies such as <code>COUNTRY#IN#CITY#PUNE</code> to query at any level.</li>
</ul>
<p>Here is the pitfall. Suppose your sort keys look like <code>ORDER#2026-10-25#A18</code> (date, then order ID). The condition <code>BETWEEN 'ORDER#2026-10-01' AND 'ORDER#2026-10-25'</code> silently drops every order placed on the 25th, because <code>ORDER#2026-10-25#A18</code> is longer than the upper bound and sorts after it. The lower bound is safe, since a shorter prefix sorts before the longer keys that start with it.</p>
<p>There are two simple fixes. Use the next day as the upper bound (<code>ORDER#2026-10-26</code>), or add a high character such as <code>~</code> to the end of the day (<code>ORDER#2026-10-25~</code>). The <code>~</code> character sorts after <code>#</code>, digits and letters in byte order, so it works when order IDs are plain alphanumeric text.</p>
<p class="code-label"><strong>Python</strong></p>
<pre><code class="language-python">import boto3
from boto3.dynamodb.conditions import Key

table = boto3.resource("dynamodb").Table("Orders")

resp = table.query(
    KeyConditionExpression=Key("PK").eq("USER#u-1001")
    &amp; Key("SK").between("ORDER#2026-10-01", "ORDER#2026-10-25~")
)
orders = resp["Items"]</code></pre>
<p>This returns all orders from 1 October to 25 October 2026 for one customer, including those placed on the 25th.</p>
<h3>How does write sharding spread a hot key?</h3>
<p>Write sharding appends a calculated or random suffix (e.g. a hash of orderId modulo N) to one logical key. The trade-off is that reads become scatter-gather: you query all N shards and merge. The animated diagram below shows the write fan-out and the read path.</p>
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/10/dynamodb-best-practices-single-table-design-diagram-3.gif" alt="Hot tenant-42 writes throttle one partition, then a hash suffix spreads them over four shards; reads query all four and merge." width="1200" height="675" /><figcaption>Write sharding spreads one hot key over N suffixed keys, and reads pay for it by querying all N shards and merging.</figcaption></figure>
<p>The simplified example below writes with a stable hash suffix and reads the newest orders from four shards. Python&#8217;s built-in <code>hash()</code> changes between processes, so use <code>hashlib</code>.</p>
<p class="code-label"><strong>Python</strong></p>
<pre><code class="language-python">import hashlib
import boto3
from boto3.dynamodb.conditions import Key

SHARDS = 4
table = boto3.resource("dynamodb").Table("Orders")

def shard_for(order_id: str) -&gt; int:
    return int(hashlib.md5(order_id.encode()).hexdigest(), 16) % SHARDS

def put_order(tenant, order_id, created_at, attrs):
    table.put_item(Item={
        "PK": f"TENANT#{tenant}#{shard_for(order_id)}",
        "SK": f"ORDER#{created_at}#{order_id}",
        **attrs,
    })

def list_orders(tenant, limit=50):
    """Return the newest `limit` orders across all shards (first page only)."""
    items = []
    for shard in range(SHARDS):
        kwargs = {
            "KeyConditionExpression": Key("PK").eq(f"TENANT#{tenant}#{shard}"),
            "ScanIndexForward": False,
            "Limit": limit,
        }
        shard_items = []
        while len(shard_items) &lt; limit:
            resp = table.query(**kwargs)
            shard_items.extend(resp["Items"])
            if "LastEvaluatedKey" not in resp:
                break
            kwargs["ExclusiveStartKey"] = resp["LastEvaluatedKey"]
            kwargs["Limit"] = limit - len(shard_items)
        items.extend(shard_items)
    items.sort(key=lambda i: i["SK"], reverse=True)
    return items[:limit]</code></pre>
<p>Each shard is read only until it has <code>limit</code> items, so the function reads at most <code>SHARDS × limit</code> items. That is enough, because the newest <code>limit</code> orders overall must be among the newest <code>limit</code> of some shard. The <code>LastEvaluatedKey</code> loop is still needed because one query response is capped at 1 MB of data.</p>
<p>For a &#8220;next page&#8221; feature, keep one <code>LastEvaluatedKey</code> per shard and resume each shard from its own cursor. To fetch every order for a tenant instead, remove the <code>limit</code> check and expect to read all items on all shards. In production, run the shard queries in parallel.</p>
<h3>What are the GSI best practices?</h3>
<p>Add a <a href="https://thecodebuzz.com/mongodb-indexes-performance-guidelines-and-best-practices/">global secondary index (GSI)</a> only for a proven access pattern. Each GSI repeats every matching write, so it adds write cost and storage. Apply the same uniform-key rule to GSI keys, because a skewed GSI key can throttle writes to the base table.</p>
<ul>
<li><strong>Sparse GSIs:</strong> only items that carry the GSI key attributes are copied. If only open orders have the key, the index stays small and cheap.</li>
<li><strong>Index overloading:</strong> use generic <code>GSI1PK</code> and <code>GSI1SK</code> so one index serves several entity types.</li>
<li><strong>GSI write sharding:</strong> shard the index key the same way as the table key.</li>
<li><strong>Narrow projections:</strong> use <code>KEYS_ONLY</code> or <code>INCLUDE</code> instead of <code>ALL</code> unless every attribute is needed.</li>
</ul>
<p>How many GSIs should a table have? As few as your proven access patterns need. The default quota has been 20 GSIs per table, but quotas can change and can be raised on request, so confirm the current number on the DynamoDB quotas page for your Region and account.</p>
<h3>What should you know about LSIs and the 10 GB item-collection limit?</h3>
<p>A local secondary index (LSI) uses the same partition key as the base table with a different sort key. It must be defined when the table is created, and the default quota has been 5 LSIs per table (confirm on the quotas page).</p>
<p>If a table has an LSI, the <strong>10 GB limit applies to each item collection</strong>, meaning all items (and their LSI entries) that share one partition key value. Writes to a collection that reaches the limit are rejected. Tables without an LSI don&#8217;t have this cap.</p>
<p>This is why an unbounded collection, such as every order for one tenant under a single partition key, is risky on a table with an LSI. Prefer a GSI when you need an alternate sort order, or bound collections with a time bucket or a shard suffix.</p>
<h3>How do you keep queries cheap?</h3>
<ul>
<li><strong>Use Query, not Scan:</strong> Query reads one item collection, while Scan reads the whole table.</li>
<li><strong>Add ProjectionExpression:</strong> return only the attributes you need.</li>
<li><strong>Use eventually consistent reads:</strong> they cost half as much when slightly stale data is acceptable.</li>
<li><strong>Don&#8217;t treat FilterExpression as an index:</strong> it filters after reading, so you still pay for all the data read.</li>
</ul>
<h2 id="transactions-consistency-replication-and-streams">Transactions, Consistency, Replication and Streams</h2>
<p>Use <strong>conditional writes</strong> for optimistic concurrency, use <code>TransactWriteItems</code> only where several items must succeed or fail together, and choose the replication model by the consistency you need.</p>
<h3>How do conditional writes prevent overwrites?</h3>
<p>Add a <code>ConditionExpression</code> to a write, and DynamoDB applies it only if the condition is true. Use <code>attribute_not_exists(PK)</code> to block overwriting an existing item. For optimistic locking, keep a <code>version</code> attribute and write with <code>version = :expected</code>, then increment it.</p>
<blockquote><p><strong>In plain English:</strong> A conditional write is like a ticket office checking the seat is still free at the moment you pay. If someone else took it first, your purchase is refused instead of silently replacing theirs.</p></blockquote>
<h3>When should you use TransactWriteItems?</h3>
<p><code>TransactWriteItems</code> is all-or-nothing across items. Keep it for cases such as moving an order status and writing a ledger item in finance. A transactional read costs 2 RRUs on-demand, against 1 for a strongly consistent read and 0.5 for an eventually consistent one.</p>
<p class="code-label"><strong>C# (.NET)</strong></p>
<pre><code class="language-csharp">using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;

// Create one client per process and reuse it.
var client = new AmazonDynamoDBClient();

var orderId = Guid.NewGuid().ToString();

var request = new TransactWriteItemsRequest
{
    ClientRequestToken = orderId, // same token on retry = same request
    TransactItems = new List&lt;TransactWriteItem&gt;
    {
        new TransactWriteItem
        {
            Put = new Put
            {
                TableName = "AppTable",
                Item = new Dictionary&lt;string, AttributeValue&gt;
                {
                    ["PK"] = new AttributeValue { S = "USER#42" },
                    ["SK"] = new AttributeValue { S = $"ORDER#{orderId}" },
                    ["entityType"] = new AttributeValue { S = "Order" }
                },
                ConditionExpression = "attribute_not_exists(PK)"
            }
        },
        new TransactWriteItem
        {
            Update = new Update
            {
                TableName = "AppTable",
                Key = new Dictionary&lt;string, AttributeValue&gt;
                {
                    ["PK"] = new AttributeValue { S = "USER#42" },
                    ["SK"] = new AttributeValue { S = "PROFILE" }
                },
                UpdateExpression = "ADD orderCount :one",
                ConditionExpression = "attribute_exists(PK)",
                ExpressionAttributeValues = new Dictionary&lt;string, AttributeValue&gt;
                {
                    [":one"] = new AttributeValue { N = "1" }
                }
            }
        }
    }
};

try
{
    await client.TransactWriteItemsAsync(request);
}
catch (TransactionCanceledException ex)
{
    foreach (var reason in ex.CancellationReasons)
        Console.WriteLine($"{reason.Code}: {reason.Message}");
}</code></pre>
<p>The order item and the customer counter commit together, or neither does. <code>CancellationReasons</code> tells you which condition failed.</p>
<h3>How should you handle retries and pagination?</h3>
<ul>
<li><strong>Trust SDK retries:</strong> The SDKs retry <a href="https://thecodebuzz.com/transient-errors-in-cloud-guidelines-and-resolution/">throttled requests with backoff</a> by default, so do not add custom tight retry loops.</li>
<li><strong>Reuse the client:</strong> Keep one client instance per process.</li>
<li><strong>Paginate:</strong> Loop on <code>LastEvaluatedKey</code> for every Query and Scan.</li>
</ul>
<h3>Which replication model fits your consistency needs?</h3>
<p>Global tables replicate across Regions. Multi-account global tables (announced Feb 3, 2026) add account-level isolation and separate governance. Multi-Region strong consistency (MRSC) is available in 15 AWS Regions as of the Sept 2026 expansion, so check your Regions first. In Oct 2026 AWS added replica disassociation, which lets a Region or account keep its table as a standalone single-Region table without copying data.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Model</th>
<th>Read freshness</th>
<th>Write latency</th>
<th>Use case</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Global table (eventual)</strong></td>
<td>Remote Regions may lag briefly</td>
<td>Local, lowest of the multi-Region options</td>
<td>Active-active apps, local reads</td>
</tr>
<tr>
<td><strong>Global table (MRSC)</strong></td>
<td>Strongly consistent across Regions</td>
<td>Higher, because Regions coordinate</td>
<td>Finance, no stale reads after failover</td>
</tr>
<tr>
<td><strong>Single Region</strong></td>
<td>Strong reads within the Region</td>
<td>Lowest</td>
<td>Simple apps, one-Region compliance</td>
</tr>
</tbody>
</table>
</figure>
<h3>What changed in DynamoDB Streams?</h3>
<p>Streams now supports the <code>AT_TIMESTAMP</code> shard iterator (announced Oct 15, 2026). A consumer can start from a point in time instead of only the oldest retained record (up to 24 hours old) or new records. It also works with KCL through the Streams Kinesis adapter.</p>
<p>In a single-table design, route stream consumers by the <code>entityType</code> attribute, so an order handler ignores customer records.</p>
<h2 id="dynamodb-cost-optimization-on-demand-vs-provisioned-and-item">DynamoDB Cost Optimization: On-Demand vs Provisioned and Item Size</h2>
<p>Start with <strong>on-demand</strong> for most workloads. Move to <a href="https://thecodebuzz.com/autoscaling-cloud-best-practices-azure-aws-google/">provisioned with auto scaling</a> only when traffic is steady and predictable. Cut cost first by shrinking items and removing unused indexes, because those savings apply in every capacity mode.</p>
<h3>Is on-demand or provisioned cheaper in DynamoDB?</h3>
<p>After the November 2024 on-demand price reduction, on-demand is commonly the default recommendation. Before that price cut, on-demand was widely seen as much more expensive for steady workloads. Provisioned capacity with auto scaling can still save money for steady traffic, but the gap has narrowed.</p>
<blockquote><p><strong>In plain English:</strong> On-demand is like paying per taxi ride, so you pay only when you travel. Provisioned is like leasing a car: cheaper per trip if you drive every day, wasted money if it sits in the garage.</p></blockquote>
<p>A secondary summary of the AWS cost-optimization page puts the break-even at about <strong>35% average utilization</strong> of provisioned capacity. That figure has not been confirmed against the AWS documentation, so treat it as unverified. It also says on-demand can still win above that level when traffic has quiet periods with occasional peaks. Check the current AWS cost-optimization page and your own CloudWatch usage data before you decide.</p>
<p>The animated diagram below shows the decision path for choosing a capacity mode.</p>
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/10/dynamodb-best-practices-single-table-design-diagram-5.gif" alt="Decision flow: new or unpredictable traffic uses on-demand; steady, high utilization uses provisioned with auto scaling; both can add a Savings Plan." width="1200" height="675" /><figcaption>Start on-demand, move to provisioned with auto scaling only for steady traffic, and re-check quarterly against CloudWatch.</figcaption></figure>
<h3>How do the capacity modes compare?</h3>
<p>This table compares the three options across the main decision factors.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Factor</th>
<th>On-demand</th>
<th>Provisioned</th>
<th>Provisioned + auto scaling</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Traffic shape</strong></td>
<td>New, spiky or unknown</td>
<td>Flat and known</td>
<td>Steady with gradual changes</td>
</tr>
<tr>
<td><strong>Throttling risk</strong></td>
<td>Low</td>
<td>High if under-provisioned</td>
<td>Medium; scaling reacts to load</td>
</tr>
<tr>
<td><strong>Planning effort</strong></td>
<td>None</td>
<td>High</td>
<td>Medium (targets and limits)</td>
</tr>
<tr>
<td><strong>Cost behaviour</strong></td>
<td>Pay per request</td>
<td>Pay for reserved units, used or not</td>
<td>Follows load, with some headroom</td>
</tr>
</tbody>
</table>
</figure>
<p><strong>AWS Database Savings Plans</strong> (launched December 2025) are a discount layer on top of a capacity mode, not a third mode. A 1-year commitment gives up to about 18% on on-demand throughput and up to about 12% on provisioned capacity.</p>
<h3>What does a read cost on-demand?</h3>
<p>Read cost depends on consistency and item size, in 4 KB steps. The table shows the on-demand read units (RRUs) per read of up to 4 KB.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Read type</th>
<th>Cost (up to 4 KB)</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Strongly consistent</strong></td>
<td>1 RRU</td>
</tr>
<tr>
<td><strong>Eventually consistent</strong></td>
<td>0.5 RRU</td>
</tr>
<tr>
<td><strong>Transactional</strong></td>
<td>2 RRUs</td>
</tr>
</tbody>
</table>
</figure>
<p>For storage, the source quotes list prices of $0.25 per GB-month for Standard and $0.10 per GB-month for Standard-IA. Confirm prices for your Region on the AWS pricing page.</p>
<h3>How do I compare the modes with my own numbers?</h3>
<p>Convert your traffic into monthly units, then multiply by the list price for your Region. The formula is requests per second x units per request x seconds in the month x price per unit. This guide does not quote throughput prices, so take them from the AWS pricing page.</p>
<p>The example below uses a simplified workload: a retail catalog service that reads a 6 KB item with strongly consistent reads, averaging 100 reads per second with a peak of 200 reads per second. It assumes a 30-day month (2,592,000 seconds, 720 hours) and provisioned capacity set flat at the peak.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Step</th>
<th>On-demand</th>
<th>Provisioned (flat at peak)</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Units per read</strong></td>
<td>6 KB rounds up to two 4 KB blocks = 2 RRUs</td>
<td>2 read units</td>
</tr>
<tr>
<td><strong>Rate used</strong></td>
<td>Average: 100 x 2 = 200 RRUs per second</td>
<td>Peak: 200 x 2 = 400 read capacity units</td>
</tr>
<tr>
<td><strong>Monthly quantity</strong></td>
<td>200 x 2,592,000 = 518.4 million RRUs</td>
<td>400 x 720 = 288,000 capacity-unit hours</td>
</tr>
<tr>
<td><strong>Monthly cost</strong></td>
<td>518.4 x on-demand price per million RRUs</td>
<td>288,000 x provisioned price per capacity-unit hour</td>
</tr>
<tr>
<td><strong>Average utilization</strong></td>
<td>Not applicable (pay per request)</td>
<td>200 / 400 = 50%</td>
</tr>
</tbody>
</table>
</figure>
<p>Plug both prices into the last row and compare the two totals. Repeat the same steps for writes, using 1 write unit per 1 KB. If you switch to eventually consistent reads, halve the read units in both columns.</p>
<p>This simplified Python script does the same arithmetic. It asks for the two prices so you can enter the current values for your Region, and you can add your own logic for writes or auto scaling.</p>
<p class="code-label"><strong>Python</strong></p>
<pre><code class="language-python">import math

SECONDS_PER_MONTH = 30 * 24 * 3600
HOURS_PER_MONTH = 30 * 24


def read_units(item_kb, strongly_consistent=True):
    """Read units for one read: 4 KB blocks, halved for eventual consistency."""
    blocks = math.ceil(item_kb / 4)
    return blocks * (1 if strongly_consistent else 0.5)


def compare_read_cost(avg_rps, peak_rps, item_kb, od_price_per_million, prov_price_per_unit_hour):
    units = read_units(item_kb)
    on_demand_units = avg_rps * units * SECONDS_PER_MONTH
    provisioned_unit_hours = peak_rps * units * HOURS_PER_MONTH
    return {
        "on_demand_cost": on_demand_units / 1_000_000 * od_price_per_million,
        "provisioned_cost": provisioned_unit_hours * prov_price_per_unit_hour,
        "avg_utilization": avg_rps / peak_rps,
    }


od_price = float(input("On-demand price per million read units: "))
prov_price = float(input("Provisioned price per read capacity unit-hour: "))
print(compare_read_cost(100, 200, 6, od_price, prov_price))
</code></pre>
<p>The script returns both monthly costs and the average utilization, so you can see which mode is cheaper for your traffic shape.</p>
<h3>How do item size and GSIs multiply cost?</h3>
<p>A write unit covers 1 KB, so a 6 KB item write costs 6 write units. A strongly consistent read of the same item costs 2 read units (6 KB rounds up to two 4 KB blocks). Every GSI that contains the item repeats the write.</p>
<p>The table shows write units for one 6 KB item under different designs. KEYS_ONLY figures assume the projected keys fit in 1 KB.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Design</th>
<th>Write units per 6 KB item</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>No GSI</strong></td>
<td>6</td>
</tr>
<tr>
<td><strong>3 GSIs, ALL projection, item in every index</strong></td>
<td>Up to 24 (6 x 4)</td>
</tr>
<tr>
<td><strong>3 GSIs, ALL projection, item in only one (sparse)</strong></td>
<td>12</td>
</tr>
<tr>
<td><strong>3 GSIs, KEYS_ONLY projection</strong></td>
<td>About 9 (6 + 3 x 1)</td>
</tr>
</tbody>
</table>
</figure>
<h3>Which other levers reduce the DynamoDB bill?</h3>
<ul>
<li><strong>Standard-IA table class:</strong> Use it for data that is stored a lot but read rarely (e.g. old retail orders).</li>
<li><strong>TTL:</strong> Expire old items such as sessions so you stop paying to store them.</li>
<li><strong>Blobs in S3:</strong> Keep only a reference in the item to shrink read and write units.</li>
<li><strong>Short attribute names:</strong> Apply only where item size is truly the cost driver, since they hurt readability.</li>
<li><strong>Eventually consistent reads:</strong> Use them where slightly stale data is acceptable, to halve read cost.</li>
<li><strong>PITR and backups:</strong> Track their storage as its own line item on the bill.</li>
</ul>
<h2 id="dynamodb-security-backups-monitoring-anti-patterns-and-produ">DynamoDB Security, Backups, Monitoring, Anti-Patterns and Production Checklist</h2>
<p>Turn on <strong>point-in-time recovery (PITR)</strong> and deletion protection, give each application least-privilege IAM access, and alarm on throttles before users notice them. DynamoDB has no servers to patch, so most of your production work is access control, recovery and watching the right metrics.</p>
<h3>How do you secure a DynamoDB table?</h3>
<p>Grant only the actions and keys each application needs, and keep traffic private. The points below cover the main controls:</p>
<ul>
<li><strong>Least-privilege IAM:</strong> Scope policies to one table, and to specific actions such as <code>dynamodb:GetItem</code> and <code>dynamodb:Query</code>. Avoid <code>dynamodb:*</code> on all tables.</li>
<li><strong>Key-prefix access:</strong> Use the <code>dynamodb:LeadingKeys</code> condition key to limit a caller to partition keys it owns (e.g. one tenant&#8217;s <code>TENANT#</code> prefix in a SaaS product).</li>
<li><strong>Encryption at rest:</strong> It is on by default. You do not need to enable it, but check which key type your compliance rules require.</li>
<li><strong>Private access:</strong> Use a VPC gateway endpoint so traffic from your VPC does not travel over the public internet.</li>
<li><strong>Account isolation:</strong> Keep production in its own account. Multi-account global tables help when replicas need separate governance.</li>
<li><strong>Sensitive data:</strong> Do not store secrets or unencrypted personal data (e.g. patient identifiers in a healthcare app) in plain attributes. Keep secrets in a secrets manager.</li>
</ul>
<h3>How do you back up and restore DynamoDB?</h3>
<p>Use PITR for continuous recovery inside its retention window, and on-demand backups for long-term copies. Both add storage cost, so treat them as a budget line item.</p>
<blockquote class="tcb-plain-english" style="border-left: 4px solid #f59e0b; background: #fffbeb; margin: 18px 0; padding: 10px 16px; font-style: normal;"><p><strong>Note :</strong> PITR is like a security camera that records continuously. If someone deletes the wrong rows at 2:10 PM, you rewind to 2:09 PM. It only keeps footage for a limited time, so older copies need on-demand backups.</p></blockquote>
<p>The retention window is configurable. You set the recovery period in the same PITR specification (the <code>RecoveryPeriodInDays</code> field), so pick a window that matches how long it could take you to notice a bad deployment or a bad delete. Check the current AWS documentation for the allowed range, and remember that a longer window means more backup storage.</p>
<p>The commands below enable PITR and deletion protection on a table named <code>Orders</code>:</p>
<p class="code-label"><strong>AWS CLI</strong></p>
<pre><code class="language-bash">aws dynamodb update-continuous-backups \
  --table-name Orders \
  --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true

aws dynamodb update-table \
  --table-name Orders \
  --deletion-protection-enabled</code></pre>
<p>The first command turns on continuous backups with the default retention window. The second blocks the table from being deleted until you switch protection off.</p>
<h3>What does a DynamoDB restore bring back, and what do you reapply?</h3>
<p>A restore always creates a new table. By default it brings back the data and the table&#8217;s GSIs and LSIs, but not auto scaling, IAM, alarms or TTL, so you must set those up again on the new table.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Item</th>
<th>Restored?</th>
<th>What you do</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Table data</strong></td>
<td>Yes</td>
<td>Verify with spot-check queries</td>
</tr>
<tr>
<td><strong>GSIs and LSIs</strong></td>
<td>Yes, by default</td>
<td>Confirm they are present and active before sending traffic</td>
</tr>
<tr>
<td><strong>Auto scaling settings</strong></td>
<td>No</td>
<td>Reapply the scaling policies if you use provisioned mode</td>
</tr>
<tr>
<td><strong>IAM policies</strong></td>
<td>No</td>
<td>Update policies to the new table name and ARN</td>
</tr>
<tr>
<td><strong>CloudWatch alarms</strong></td>
<td>No</td>
<td>Recreate the throttle and error alarms</td>
</tr>
<tr>
<td><strong>TTL setting</strong></td>
<td>No</td>
<td>Enable TTL again on the expiry attribute</td>
</tr>
</tbody>
</table>
</figure>
<p>Keep these settings in infrastructure-as-code so reapplying them is a repeatable step, not a manual checklist. Also check the AWS restore documentation for other table settings (e.g. stream settings and tags) that you may need to review. Rehearse the restore on a schedule so the first time you do it is not during an incident.</p>
<h3>What changes for operations and upgrades?</h3>
<p>Nothing needs patching. There are no OS settings, memory tuning, maintenance windows or version upgrades, because features ship continuously. Instead, review new announcements during architecture reviews (e.g. Streams <code>AT_TIMESTAMP</code>, vector search, replica disassociation).</p>
<p>Use TTL to expire old items. Expiry is not instant, so filter expired items in reads if stale data would cause problems.</p>
<h3>Which metrics should you monitor?</h3>
<p>Alarm on throttling and errors first, then watch consumption. Track <code>ThrottledRequests</code>, <code>ReadThrottleEvents</code>, <code>WriteThrottleEvents</code>, <code>SystemErrors</code>, <code>ConsumedReadCapacityUnits</code>, <code>ConsumedWriteCapacityUnits</code> and, for global tables, <code>ReplicationLatency</code>.</p>
<p>Enable CloudWatch Contributor Insights to see the most accessed and most throttled keys. It is the fastest way to confirm a DynamoDB hot partition.</p>
<h3>What are the common DynamoDB anti-patterns?</h3>
<p>This table maps each mistake to what you will see and how to fix it:</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Anti-pattern</th>
<th>Symptom</th>
<th>Fix</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Timestamp or status as partition key</strong></td>
<td>Throttling on a few keys</td>
<td>Use a high-cardinality key such as <code>orderId</code></td>
</tr>
<tr>
<td><strong>Scan in the request path</strong></td>
<td>Slow reads, high read cost</td>
<td>Use Query with a purpose-built key or GSI</td>
</tr>
<tr>
<td><strong>One GSI per idea</strong></td>
<td>High write cost and storage</td>
<td>Keep only proven indexes; use sparse and overloaded GSIs</td>
</tr>
<tr>
<td><strong>Blobs stored inline</strong></td>
<td>Large items, expensive reads and writes</td>
<td>Store in S3, keep a reference</td>
</tr>
<tr>
<td><strong>Unbounded item collection with huge items</strong></td>
<td>One key grows and gets hot</td>
<td>Split the key or shard it</td>
</tr>
<tr>
<td><strong>FilterExpression as an index</strong></td>
<td>Paying to read data you discard</td>
<td>Model the filter into the key or a GSI</td>
</tr>
<tr>
<td><strong>Single table on a simple, changing domain</strong></td>
<td>Hard-to-read model, painful changes</td>
<td>Use separate tables</td>
</tr>
<tr>
<td><strong>Over-provisioned capacity left unchanged</strong></td>
<td>Low utilization, high bill</td>
<td>Review the capacity mode and auto scaling</td>
</tr>
<tr>
<td><strong>No PITR or deletion protection</strong></td>
<td>Accidental loss is permanent</td>
<td>Enable both</td>
</tr>
<tr>
<td><strong>Hot tenant, no sharding</strong></td>
<td>One large tenant is throttled</td>
<td>Add a write-shard suffix to the key</td>
</tr>
</tbody>
</table>
</figure>
<h3>Production readiness checklist</h3>
<p>Work through these steps in order before go-live:</p>
<ol>
<li><strong>List access patterns:</strong> Test each one with a real Query.</li>
<li><strong>Check key cardinality:</strong> Confirm traffic spreads evenly across partition keys.</li>
<li><strong>Justify every GSI:</strong> Document each index and its projection.</li>
<li><strong>Set an item size and blob policy:</strong> Decide what goes to S3.</li>
<li><strong>Choose the capacity mode:</strong> Document why.</li>
<li><strong>Enable PITR and deletion protection:</strong> Set the PITR retention window deliberately, and add TTL where data expires.</li>
<li><strong>Apply least-privilege IAM:</strong> Use <code>dynamodb:LeadingKeys</code> where callers share a table.</li>
<li><strong>Configure alarms:</strong> Alert on throttles, and enable Contributor Insights.</li>
<li><strong>Run a restore test:</strong> Check that the data and GSIs/LSIs are present, then reapply auto scaling, IAM, TTL and alarms from your infrastructure-as-code.</li>
<li><strong>Load-test the hottest key:</strong> Compare results with the per-partition limits.</li>
</ol>
<h2 id="key-takeaways">Key takeaways</h2>
<p>These are the points to remember from the guide, in the order you will usually need them.</p>
<ul>
<li><strong>Design from access patterns first:</strong> list every read and write before you choose keys. Single-table design is a tool for known, related, high-volume patterns, not a universal rule. Use separate tables when entities scale or fail independently, or when patterns are simple or still changing.</li>
<li><strong>Use a high-cardinality partition key:</strong> one partition is designed for up to 3,000 read units and 1,000 write units per second, and item size counts toward that. Adaptive capacity helps with uneven traffic, but it cannot lift the cap for one hot key. Avoid timestamps and status values as partition keys, and use write sharding when one logical key is genuinely hot.</li>
<li><strong>Keep GSIs few, sparse and narrowly projected:</strong> every GSI repeats the write, so it adds write cost and storage. Add one only for a proven access pattern, and prefer KEYS_ONLY or INCLUDE over ALL. Apply the same even-spread rule to GSI keys, because a skewed index key can throttle base-table writes.</li>
<li><strong>Prefer Query over Scan:</strong> use <code>ProjectionExpression</code> and eventually consistent reads where staleness is acceptable. <code>FilterExpression</code> is not an index, because you still pay for everything it reads before filtering.</li>
<li><strong>Use the right tool for consistency:</strong> use conditional writes for optimistic concurrency, and <code>TransactWriteItems</code> only when several items must succeed or fail together. Transactional reads cost more than normal reads. Pick the global table model (eventual consistency, MRSC or single Region) by the freshness you actually need.</li>
<li><strong>Start on-demand, then measure:</strong> move to provisioned with auto scaling only when traffic is steady and predictable. Check the roughly 35% utilization break-even against the current AWS cost-optimization page and your own usage data, since it comes from a secondary summary. Database Savings Plans are a discount layer on top of a capacity mode, not a third mode.</li>
<li><strong>Treat item size as a cost driver:</strong> keep large blobs in S3 and store only the reference in the item. Use TTL to expire old data and Standard-IA for rarely read tables, and watch PITR and backup storage as a line item.</li>
<li><strong>Protect and observe the table:</strong> enable PITR and deletion protection, apply least-privilege IAM, and alarm on throttle metrics. Use Contributor Insights to confirm hot keys, and run restore tests on a schedule.</li>
<li><strong>Review new features when you revisit the design:</strong> DynamoDB has no versions, so check announcements such as multi-account global tables, MRSC, replica disassociation, Streams AT_TIMESTAMP and vector search. Each may simplify an architecture you built around older limits.</li>
</ul>
<h2 id="faq">FAQ</h2>
<h3><strong>Is single-table design always the best approach in DynamoDB?</strong></h3>
<p>No. Single-table design pays off when your access patterns are known, related and high volume, because one Query can return several entity types from the same partition key. Use separate tables when entities scale or fail independently, need separate IAM, backup scope or blast radius, or when the access patterns are simple or still changing.</p>
<h3><strong>How do I choose a good partition key in DynamoDB?</strong></h3>
<p>Choose an attribute with high cardinality (many distinct values) whose traffic is spread evenly, and that matches your main lookup, such as <code>customerId</code> or <code>orderId</code>. Avoid timestamps and status or boolean values, because they send most traffic to a few key values. Apply the same rule to the keys of your GSIs, since a skewed index key can throttle base-table writes.</p>
<h3><strong>What is a hot partition and how do I fix it?</strong></h3>
<p>A hot partition is a partition that receives more traffic than its limit, so requests get throttled even when the table as a whole is well under its capacity. Confirm it with CloudWatch Contributor Insights, which shows the most accessed and most throttled keys. Then fix it with a better partition key, write sharding (a calculated suffix that spreads one logical key across N keys), or caching for read-heavy keys. Adaptive capacity helps uneven traffic, but it cannot lift the hard limit for a single hot key.</p>
<h3><strong>What are the throughput limits per partition in DynamoDB?</strong></h3>
<p>A partition is designed to deliver up to 3,000 read units and 1,000 write units per second, and item size counts toward both limits. A read unit is one strongly consistent read (or two eventually consistent reads) per second for an item up to 4 KB. For example, a 20 KB item costs 5 read units per strongly consistent read, so about 600 reads per second on that one item reaches the partition limit.</p>
<h3><strong>Should I use on-demand or provisioned capacity?</strong></h3>
<p>Start with on-demand for most workloads, because it needs no capacity planning and has lower throttling risk for spiky traffic. Move to provisioned with auto scaling when traffic is steady and predictable. One secondary summary of AWS guidance puts the break-even at roughly 35% average utilization of provisioned capacity, so check that figure against the current AWS cost-optimization page and your own usage data. AWS Database Savings Plans are a discount on top of either mode, not a third mode.</p>
<p><strong>That&#8217;s all! Happy coding!</strong> Did this DynamoDB best practices guide help you solve your design or cost issue? Please share your questions or experience in the comments below. Bookmark this page and share it with your team, and subscribe to TheCodeBuzz for more database best-practice guides.</p>
<h2 id="sources">Sources and further reading</h2>
<ul>
<li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html" target="_blank" rel="noopener">Best practices for designing and using partition keys effectively in DynamoDB</a> (AWS Documentation (Amazon DynamoDB Developer Guide))</li>
<li><a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/dynamodb-data-modeling/best-practices.html" target="_blank" rel="noopener">Best practices &#8211; AWS Prescriptive Guidance (DynamoDB data modeling)</a> (AWS Prescriptive Guidance)</li>
<li><a href="https://aws.amazon.com/about-aws/whats-new/2026/08/amazon-dynamodb-vector-search/" target="_blank" rel="noopener">Amazon DynamoDB now supports real-time vector search</a> (AWS What&#8217;s New)</li>
<li><a href="https://aws.amazon.com/about-aws/whats-new/2026/10/dynamodb-global-tables-disassociate/" target="_blank" rel="noopener">Amazon DynamoDB global tables now support disassociating replicas</a> (AWS What&#8217;s New)</li>
<li><a href="https://aws.amazon.com/about-aws/whats-new/2026/10/amazon-dynamodb-streams-timestamp-processing/" target="_blank" rel="noopener">Amazon DynamoDB Streams now supports timestamp-based stream processing</a> (AWS What&#8217;s New)</li>
</ul>
<p>&nbsp;</p><p>The post <a href="https://thecodebuzz.com/dynamodb-best-practices-single-table-design/">DynamoDB Best Practices: Single-Table Design, Keys and Cost</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/dynamodb-best-practices-single-table-design/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Cassandra Best Practices: 17 Rules for Data and Ops</title>
		<link>https://thecodebuzz.com/cassandra-best-practices-guidelines/</link>
					<comments>https://thecodebuzz.com/cassandra-best-practices-guidelines/#comments</comments>
		
		<dc:creator><![CDATA[Izzy]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 02:51:21 +0000</pubDate>
				<category><![CDATA[Database Best Practices]]></category>
		<category><![CDATA[Cassandra]]></category>
		<category><![CDATA[Cassandra 5.0]]></category>
		<category><![CDATA[Data Modeling]]></category>
		<category><![CDATA[NoSQL]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=30906</guid>

					<description><![CDATA[<p>Cassandra best practices in 17 rules: partition keys, data modeling, LOCAL_QUORUM, tombstones, repair and compaction, each with a check. Run on 5.0.9.</p>
<p>The post <a href="https://thecodebuzz.com/cassandra-best-practices-guidelines/">Cassandra Best Practices: 17 Rules for Data and Ops</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph">Your Cassandra cluster works in testing, then reads slow down, <code>nodetool</code> logs tombstone warnings, or a node restart becomes an outage. These <strong>Cassandra best practices</strong> cover the 17 choices behind most of those problems, each with what to do, why it helps and how to check it on your own cluster.</p>



<p class="wp-block-paragraph"><strong>Quick answer:</strong> model one table per query, keep every partition under about 100 MB and 100,000 values, never filter without the partition key, use TTL instead of deletes, run <code>LOCAL_QUORUM</code> with RF=3 per datacenter on <code>NetworkTopologyStrategy</code>, finish repair inside <code>gc_grace_seconds</code>, pick the compaction strategy on purpose, and test your restores. Examples marked as run used Cassandra 5.0.9.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/cassbp-partition-buckets-1.png" alt="Diagram comparing one 25.1 MB Cassandra partition holding 200,000 sensor readings with 24 daily partitions of at most 1.1 MB, with the traced read times measured on Cassandra 5.0.9"/></figure>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#cassandra-best-practices-at-a-glance">Cassandra Best Practices at a Glance</a></li><li><a href="#cassandra-data-modeling-best-practices-and-partition-key-des">Cassandra Data Modeling Best Practices and Partition Key Design</a></li><li><a href="#indexing-in-cassandra-5-0-sai-secondary-indexes-or-more-tabl">Indexing in Cassandra 5.0: SAI, Secondary Indexes or More Tables</a></li><li><a href="#consistency-levels-and-replication-factor-choosing-local-quo">Consistency Levels and Replication Factor: Choosing LOCAL_QUORUM</a></li><li><a href="#transactions-and-lightweight-transactions-paxos-v2-and-accor">Transactions, Counters and Collections: Lightweight Transactions and Their Limits</a></li><li><a href="#tombstones-ttl-and-gc-grace-seconds-deleting-data-safely">Tombstones, TTL and gc_grace_seconds: Deleting Data Safely</a></li><li><a href="#choosing-a-compaction-strategy-stcs-lcs-twcs-or-ucs">Choosing a Compaction Strategy: STCS, LCS, TWCS or UCS</a></li><li><a href="#drivers-connection-management-and-security">Drivers, Connection Management and Security</a></li><li><a href="#repair-backup-and-restore-best-practices">Repair, Backup and Restore Best Practices</a></li><li><a href="#operations-monitoring-and-upgrades">Operations, Monitoring and Upgrades</a></li><li><a href="#key-takeaways">Key takeaways</a></li><li><a href="#faq">FAQ</a></li><li><a href="#sources">Sources and further reading</a></li></ul></div>



<h2 class="wp-block-heading" id="cassandra-best-practices-at-a-glance">Cassandra Best Practices at a Glance</h2>



<p class="wp-block-paragraph">A partition is the unit Cassandra stores, replicates, reads, compacts and repairs. Every row with the same partition key lives in one partition on a fixed set of replicas, so most practices below keep that unit small, evenly spread and cheap to read.</p>



<h3 class="wp-block-heading">Best Practices Summary</h3>



<ul class="wp-block-list">
<li><strong>Data model (1 to 3):</strong> one table per query, a high-cardinality partition key, bounded partitions and time buckets.</li>

<li><strong>Reads (4 to 6):</strong> no <code>ALLOW FILTERING</code>, SAI instead of legacy indexes, small <code>IN</code> lists and batches.</li>

<li><strong>Consistency and writes (7 to 10):</strong> <code>LOCAL_QUORUM</code> with RF=3, rare lightweight transactions, careful counters and collections, TTL over deletes.</li>

<li><strong>Storage and clients (11 to 13):</strong> a deliberate compaction strategy, one prepared and token-aware session, authentication and TLS.</li>

<li><strong>Operations (14 to 17):</strong> repair inside <code>gc_grace_seconds</code>, tested restores, monitored disks and heap, rolling upgrades.</li>
</ul>



<h3 class="wp-block-heading">Which Cassandra Version Does This Guide Assume?</h3>



<p class="wp-block-paragraph">Facts were checked on 2026-11-26 against the <a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/data-modeling/intro.html" target="_blank" rel="noopener">Apache Cassandra 5.0 documentation</a> and the download page (5.0.9 is the latest GA release, 4.1.12 and 4.0.21 are older lines). Examples marked as run were executed on one local 5.0.9 node (Java 17, cqlsh 6.2.0). Anything that needs several nodes, TLS, authentication or real traffic is labelled <em>not run</em>.</p>



<h2 class="wp-block-heading" id="cassandra-data-modeling-best-practices-and-partition-key-des">Cassandra Data Modeling Best Practices and Partition Key Design</h2>



<p class="wp-block-paragraph">Design from your queries, not from your entities. For background on modeling in general see <a href="https://thecodebuzz.com/what-is-data-modelling-fundamentals-sql-nosql-guidelines/">data modelling fundamentals for SQL and NoSQL</a>.</p>



<h3 class="wp-block-heading">1. Model one table per query and denormalize</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> List the queries first, create one table per query and write to each. Put the sort and range columns after the partition key and set <code>CLUSTERING ORDER BY</code>, then read with a range and <code>LIMIT</code> instead of sorting in code. The official <a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/data-modeling/intro.html" target="_blank" rel="noopener">data modeling guide</a> treats duplicated data as normal. Example (run):</li>

<li><strong>Why:</strong> A query that touches one partition is answered by one set of replicas, and rows inside a partition are stored sorted by the clustering columns, so &#8220;newest 100&#8221; is a contiguous slice. There are no joins, so the join work is done once at write time.</li>

<li><strong>How to check:</strong> <code>TRACING ON</code> in cqlsh: the read should show one <code>Executing single-partition query</code> line, and <code>Read N live rows</code> should be close to the rows you asked for.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE TABLE bp.orders_by_customer (
  customer_id uuid,
  order_id    timeuuid,
  status      text,
  total       decimal,
  PRIMARY KEY ((customer_id), order_id)
) WITH CLUSTERING ORDER BY (order_id DESC);

-- A second table, orders_by_id (order_id PRIMARY KEY), serves &quot;find one order by id&quot;.
</pre></div>


<h3 class="wp-block-heading">2. Pick a high-cardinality partition key that every query supplies</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Use the column your queries always filter by with equality and that has many distinct values, such as <code>customer_id</code>. Avoid <code>country</code> or <code>status</code> as the whole key. If one value is very busy, add a bucket (practice 3).</li>

<li><strong>Why:</strong> The partition key is hashed to choose replicas. Many distinct keys spread rows and traffic across nodes, and a few distinct keys pile everything on a few nodes.</li>

<li><strong>How to check:</strong> <code>nodetool tablestats keyspace.table</code>: compare <em>Compacted partition maximum bytes</em> with the mean. A maximum far above the mean marks a hot or oversized key.</li>
</ul>



<h3 class="wp-block-heading">3. Keep partitions bounded and bucket time series</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Estimate rows times columns per partition before launch. The <a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/data-modeling/intro.html" target="_blank" rel="noopener">data modeling intro</a> gives the guideline of below 100,000 values and below 100 MB per partition, and the refining guide states the hard limit of 2 billion cells. For data that grows forever, such as one sensor every few seconds, add a day or hour to the partition key and query bucket by bucket. The <code>partition_size_warn_threshold</code> guardrail in <code>cassandra.yaml</code> (disabled by default) can warn you (not run). Table (run):</li>

<li><strong>Why:</strong> A partition is read, compacted, repaired and streamed as a unit, so the bigger it is, the more memory and I/O each step needs. Each bucket is a new bounded partition, and old buckets stop receiving writes, which also suits TWCS (practice 11).</li>

<li><strong>How to check:</strong> <code>nodetool tablehistograms keyspace table</code> (Partition Size and Cell Count columns) and <em>Compacted partition maximum bytes</em> in <code>tablestats</code>, checked again as data grows. A query across several days now needs one query per bucket.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE TABLE bp.readings_bucketed (
  sensor_id    text,
  day_bucket   date,
  reading_time timestamp,
  payload      text,
  PRIMARY KEY ((sensor_id, day_bucket), reading_time)
) WITH CLUSTERING ORDER BY (reading_time DESC);
</pre></div>


<h3 class="wp-block-heading">Worked example 1: one partition against daily buckets (run)</h3>



<p class="wp-block-paragraph">I loaded the same 200,000 readings (one every 10 seconds, 100-character payload, about 23 days) into two tables: <code>readings_unbounded</code> with <code>PRIMARY KEY (sensor_id, reading_time)</code> and the bucketed table above. After <code>nodetool flush</code> and <code>nodetool compact</code>, <code>tablestats</code> reported:</p>


<div class="wp-block-syntaxhighlighter-code ">
Table: readings_unbounded
    Number of partitions (estimate): 1
    Compacted partition maximum bytes: 25109160

Table: readings_bucketed
    Number of partitions (estimate): 24
    Compacted partition maximum bytes: 1131752
</div>


<p class="wp-block-paragraph">Then I traced reads (<code>CONSISTENCY ONE; PAGING OFF; TRACING ON;</code>). The elapsed time is the last column of the <em>Request complete</em> trace line, in microseconds, from two runs:</p>


<div class="wp-block-syntaxhighlighter-code ">
SELECT count(*) FROM bp.readings_unbounded WHERE sensor_id=&#039;sensor-1001&#039;;
  Read 200000 live rows and 0 tombstone cells   Request complete: 325387 / 251841 us

SELECT count(*) FROM bp.readings_unbounded WHERE sensor_id=&#039;sensor-1001&#039;
  AND reading_time &gt;= &#039;2026-10-10&#039; AND reading_time &lt; &#039;2026-10-11&#039;;
  Read 8640 live rows and 0 tombstone cells     Request complete: 18476 / 11857 us

SELECT count(*) FROM bp.readings_bucketed
  WHERE sensor_id=&#039;sensor-1001&#039; AND day_bucket=&#039;2026-10-10&#039;;
  Read 8640 live rows and 0 tombstone cells     Request complete: 14067 / 12379 us
</div>


<p class="wp-block-paragraph">What this shows, honestly: a bounded clustering range inside the big partition was about as fast as the bucket, so a bucket does not make a single read faster. It caps the size of each partition (25.1 MB against at most 1.1 MB here, growing about 1.1 MB per day for this one sensor) and stops a plain <code>WHERE sensor_id = ?</code> from turning into a 200,000-row read. Timings are one local node with one replica and vary between runs.</p>



<h2 class="wp-block-heading" id="indexing-in-cassandra-5-0-sai-secondary-indexes-or-more-tabl">Indexing in Cassandra 5.0: SAI, Secondary Indexes or More Tables</h2>



<h3 class="wp-block-heading">4. Never use ALLOW FILTERING in application queries</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Query by partition key, or create a table for the query (practice 1). Without it, Cassandra refuses the query, as it did here (run):</li>

<li><strong>Why:</strong> Filtering without a key restriction scans partitions, and the <a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/cql/dml.html" target="_blank" rel="noopener">CQL documentation</a> says the performance of such a query can be unpredictable because it grows with the data.</li>

<li><strong>How to check:</strong> Search the code for <code>ALLOW FILTERING</code>. The <code>allow_filtering_enabled</code> guardrail in <code>cassandra.yaml</code> can switch it off (not run).</li>
</ul>


<div class="wp-block-syntaxhighlighter-code ">
cqlsh&gt; SELECT * FROM bp.orders_by_customer WHERE status=&#039;SHIPPED&#039;;
InvalidRequest: Error from server: code=2200 [Invalid query] message=&quot;Cannot execute this query
as it might involve data filtering and thus may have unpredictable performance. If you want to
execute this query despite the performance unpredictability, use ALLOW FILTERING&quot;
</div>


<h3 class="wp-block-heading">5. Use Storage-Attached Indexes for secondary lookups, not legacy indexes</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> For a secondary filter, create an SAI index and keep a partition key restriction when you can. Wait for the index build to finish before querying: my first query straight after <code>CREATE INDEX</code> failed with <code>INDEX_NOT_AVAILABLE</code> and worked a few seconds later (run).</li>

<li><strong>Why:</strong> A legacy secondary index is a per-node structure, so the <a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/cql/dml.html" target="_blank" rel="noopener">documentation</a> notes that its results depend on the number of nodes. SAI is the index introduced in 5.0. Without a partition key, an index query can still involve many nodes, so it does not replace practice 1.</li>

<li><strong>How to check:</strong> Test on production-size data with <code>TRACING ON</code>; small test sets hide fan-out cost.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE INDEX IF NOT EXISTS orders_status_sai
  ON bp.orders_by_customer (status) USING &#039;sai&#039;;

SELECT order_id, status, total FROM bp.orders_by_customer
WHERE customer_id = 7b1f3c52-8a6e-4c1d-9d0e-3f2a5b6c7d88 AND status = &#039;SHIPPED&#039;;
</pre></div>


<h3 class="wp-block-heading">6. Keep IN lists and batches small</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Run several prepared single-partition queries in parallel instead of one huge <code>IN</code> on the partition key. Use a logged batch only to keep a few denormalized tables in step, and an <code>UNLOGGED</code> batch only for rows of one partition.</li>

<li><strong>Why:</strong> An <code>IN</code> on the partition key makes the coordinator fetch each partition and wait for all of them. The <a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/cql/dml.html" target="_blank" rel="noopener">documentation</a> says a logged batch across partitions has a performance penalty for atomicity, and an unlogged batch that fails can be partly applied. Batches are not a speed tool.</li>

<li><strong>How to check:</strong> Watch <code>system.log</code> for batch warnings. The <a href="https://cassandra.apache.org/doc/5.0/cassandra/managing/configuration/cass_yaml_file.html" target="_blank" rel="noopener">cassandra.yaml reference</a> lists <code>batch_size_warn_threshold</code> (5KiB), <code>batch_size_fail_threshold</code> (50KiB) and <code>unlogged_batch_across_partitions_warn_threshold</code> (10). I did not trigger these warnings.</li>
</ul>



<h2 class="wp-block-heading" id="consistency-levels-and-replication-factor-choosing-local-quo">Consistency Levels and Replication Factor: Choosing LOCAL_QUORUM</h2>



<h3 class="wp-block-heading">7. Use RF=3 per datacenter, LOCAL_QUORUM and NetworkTopologyStrategy</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Create keyspaces with <code>NetworkTopologyStrategy</code>, give each datacenter an explicit RF of 3 using the datacenter names your snitch reports, and use <code>LOCAL_QUORUM</code> as the default (<code>CONSISTENCY LOCAL_QUORUM;</code> in cqlsh, or the driver default in practice 12). The documentation says all production deployments should use <code>NetworkTopologyStrategy</code>. After raising an RF, run a full repair (practice 14), and raise <code>system_auth</code> replication to 3 to 5 per datacenter (practice 13). Run on a one-node cluster whose datacenter is <code>datacenter1</code>:</li>

<li><strong>Why:</strong> A quorum is a majority, n/2 + 1 replicas, which is 2 of 3. Writes of 2 plus reads of 2 is 4, more than RF=3, so every read overlaps a replica that has the latest write. With two datacenters at RF=3 there are 6 replicas, so plain <code>QUORUM</code> needs 4 and must cross the WAN, while <code>LOCAL_QUORUM</code> needs 2 of 3 locally and keeps working if the other datacenter is down. <code>ALL</code> fails when any one replica is down. <code>SimpleStrategy</code> ignores topology.</li>

<li><strong>How to check:</strong> <code>DESCRIBE KEYSPACE</code> for the replication map and <code>nodetool status</code> for node state (datacenter names must match). Consistency behavior was not run on a multi-node cluster.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE KEYSPACE retail
  WITH replication = {&#039;class&#039;: &#039;NetworkTopologyStrategy&#039;, &#039;datacenter1&#039;: 3};
-- Warnings: Your replication factor 3 for keyspace retail is higher than the number
-- of nodes 1 for datacenter datacenter1
</pre></div>


<figure class="wp-block-table"><table><thead><tr><th>Level</th><th>Replicas needed (2 DCs, RF=3 each)</th><th>Use it for</th></tr></thead><tbody><tr><td><code>LOCAL_ONE</code> / <code>ONE</code></td><td>1</td><td>Data where a stale read is acceptable</td></tr><tr><td><code>LOCAL_QUORUM</code></td><td>2 of 3 in the local DC</td><td>Default for multi-DC production</td></tr><tr><td><code>QUORUM</code></td><td>4 of 6, crosses DCs</td><td>Single-DC clusters</td></tr><tr><td><code>EACH_QUORUM</code></td><td>2 of 3 in every DC</td><td>Rare writes that must reach every DC</td></tr><tr><td><code>ALL</code></td><td>6 of 6</td><td>Almost never</td></tr></tbody></table></figure>



<h2 class="wp-block-heading" id="transactions-and-lightweight-transactions-paxos-v2-and-accor">Transactions, Counters and Collections: Lightweight Transactions and Their Limits</h2>



<h3 class="wp-block-heading">8. Use lightweight transactions rarely and set Paxos v2</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Use <code>IF</code> conditions only where two writers must not both succeed, such as a unique email, and check the <code>[applied]</code> column in code. The <a href="https://cassandra.apache.org/doc/5.0/cassandra/managing/configuration/cass_yaml_file.html" target="_blank" rel="noopener">cassandra.yaml reference</a> marks <code>paxos_variant: v2</code> as recommended and safe with <code>paxos_state_purging: repaired</code>; roll it out node by node (not run, needs a rolling restart). Run:</li>

<li><strong>Why:</strong> Paxos needs several round trips between replicas.</li>

<li><strong>How to check:</strong> Compare client-side latency for LWT and plain writes, and check <code>[applied]</code> is handled.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE TABLE bp.users_by_email (email text PRIMARY KEY, user_id uuid, created_at timestamp);
INSERT INTO bp.users_by_email (email, user_id, created_at)
  VALUES (&#039;asha@example.com&#039;, uuid(), toTimestamp(now())) IF NOT EXISTS;
</pre></div>

<div class="wp-block-syntaxhighlighter-code ">
 [applied]
&#8212;&#8212;&#8212;&#8211;
      True
(second identical INSERT)
 [applied] | email            | created_at                      | user_id
&#8212;&#8212;&#8212;&#8211;+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;+&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;+&#8212;&#8212;&#8212;
     False | asha@example.com | 2026-11-23 18:46:04.487000+0000 | 71f24524-&#8230;
</div>


<h3 class="wp-block-heading">9. Treat counters as approximate and keep collections small</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Keep counters in a table that holds only counters, give them no TTL, and do not use them where an exact value matters (money, stock). Use <code>set</code>, <code>list</code> or <code>map</code> for a handful of values such as phone numbers, and clustering rows for data that grows. Run:</li>

<li><strong>Why:</strong> The types documentation lists the limits: counters cannot be in the primary key, a counter table can hold only counters, and counters do not expire. It warns that replaying an update after a timeout may or may not over-count. Collections are meant for relatively small amounts of data, are not indexed internally, and reading one element reads the whole collection.</li>

<li><strong>How to check:</strong> Reconcile counters against an event table now and then, and do not auto-retry counter updates blindly. For collections, check <code>nodetool tablehistograms</code> cell counts and trace the read.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE TABLE bp.page_hits (page text PRIMARY KEY, hits counter);
UPDATE bp.page_hits SET hits = hits + 1 WHERE page = &#039;home&#039;;

CREATE TABLE bp.profiles (user_id uuid PRIMARY KEY, phones set&lt;text&gt;);
UPDATE bp.profiles SET phones = phones + {&#039;+1-555-0100&#039;}
  WHERE user_id = 7b1f3c52-8a6e-4c1d-9d0e-3f2a5b6c7d88;
</pre></div>


<h2 class="wp-block-heading" id="tombstones-ttl-and-gc-grace-seconds-deleting-data-safely">Tombstones, TTL and gc_grace_seconds: Deleting Data Safely</h2>



<h3 class="wp-block-heading">10. Prefer TTL and time buckets over deletes, and never write nulls</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Let data expire with <code>default_time_to_live</code> or <code>USING TTL</code>, keep time series on TWCS, and leave unknown columns out of the <code>INSERT</code> (or use the driver&#8217;s unset value) instead of writing <code>null</code>. Avoid queue tables (insert, read, delete in one partition) and do not lower <code>gc_grace_seconds</code> unless repair runs more often. Run:</li>

<li><strong>Why:</strong> A delete writes a tombstone that is kept for <code>gc_grace_seconds</code> (default 864000, 10 days) and removed only by compaction, so reads must step over it. A tombstone is also how a replica learns about a delete, which is why repair must finish inside that window (practice 14). The <a href="https://cassandra.apache.org/doc/5.0/cassandra/managing/configuration/cass_yaml_file.html" target="_blank" rel="noopener">yaml reference</a> sets <code>tombstone_warn_threshold</code> to 1000 and <code>tombstone_failure_threshold</code> to 100000 per read.</li>

<li><strong>How to check:</strong> <code>system.log</code> warnings, <code>nodetool tablestats</code> (<em>Average/Maximum tombstones per slice</em>) and <code>TRACING ON</code> (<em>Read N live rows and M tombstone cells</em>).</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
CREATE TABLE bp.cart_events (
  user_id uuid, day_bucket date, event_time timestamp, event_type text,
  PRIMARY KEY ((user_id, day_bucket), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC)
  AND default_time_to_live = 604800
  AND compaction = {&#039;class&#039;: &#039;TimeWindowCompactionStrategy&#039;,
                    &#039;compaction_window_unit&#039;: &#039;DAYS&#039;, &#039;compaction_window_size&#039;: 1};

INSERT INTO bp.cart_events (user_id, day_bucket, event_time, event_type)
VALUES (uuid(), &#039;2026-11-23&#039;, toTimestamp(now()), &#039;add_to_cart&#039;) USING TTL 86400;
</pre></div>


<h3 class="wp-block-heading">Worked example 2: a queue table and a tombstone warning (run)</h3>



<p class="wp-block-paragraph">I inserted 3,000 jobs into one partition of <code>jobs_queue</code> (<code>PRIMARY KEY (queue, job_id)</code>), deleted 2,999 of them one by one, then read one row. The same pattern with an hourly bucket (<code>jobs_bucketed</code>, <code>PRIMARY KEY ((queue, hour_bucket), job_id)</code>) kept the live job in a new bucket. The trace and log showed:</p>


<div class="wp-block-syntaxhighlighter-code ">
&#8212; queue table (one partition)
Read 1 live rows and 2999 tombstone cells (see tombstone_warn_threshold)
WARN [ReadStage-3] ReadCommand.java:644 &#8211; Read 1 live rows and 2999 tombstone cells for query
  SELECT body FROM bp.jobs_queue WHERE queue = &#039;emails&#039; LIMIT 1 ALLOW FILTERING;
  token 5755870324934700989 (see tombstone_warn_threshold)
Request complete: 6493 us
nodetool tablestats: Average tombstones per slice (last five minutes): 3311.0

&#8212; bucketed table, read of the current bucket
Read 1 live rows and 0 tombstone cells
Request complete: 899 us
</div>


<p class="wp-block-paragraph">The warning appeared at the 1000 default threshold. The bucketed read avoided it because consumed jobs sit in an old bucket that is no longer read. Explicit nulls do the same on a small scale: a row inserted with two <code>null</code> columns traced as 2 tombstone cells, and the same row with those columns left out traced as 0 (run).</p>



<h2 class="wp-block-heading" id="choosing-a-compaction-strategy-stcs-lcs-twcs-or-ucs">Choosing a Compaction Strategy: STCS, LCS, TWCS or UCS</h2>



<h3 class="wp-block-heading">11. Choose the compaction strategy per table, and keep spare disk</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> The compaction overview recommends UCS for most workloads and for new tables, and STCS is still the default when nothing is set. TWCS is recommended for time-series and TTL data, and LCS for read-heavy workloads where UCS is not used. To move an STCS table to UCS with equivalent behavior, use <code>T4</code> (the docs give <code>L10</code> for LCS). Change one table at a time, staging first:</li>

<li><strong>Why:</strong> Compaction merges SSTables to drop overwritten data and expired tombstones. TWCS groups data into time windows and drops a whole SSTable when everything in it has expired, which only works if data is not written out of order. STCS needs free disk while it merges large SSTables.</li>

<li><strong>How to check:</strong> <code>nodetool compactionstats</code> (a pending count that keeps growing means compaction cannot keep up) and <em>SSTable count</em> in <code>nodetool tablestats</code>. I ran the <code>ALTER</code> below on a tiny table, which proves the syntax, not the tuning.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
ALTER TABLE bp.orders_by_customer
WITH compaction = {&#039;class&#039;: &#039;UnifiedCompactionStrategy&#039;, &#039;scaling_parameters&#039;: &#039;T4&#039;};
</pre></div>


<h2 class="wp-block-heading" id="drivers-connection-management-and-security">Drivers, Connection Management and Security</h2>



<h3 class="wp-block-heading">12. Create one session, prepare statements, be token-aware, and retry only idempotent statements</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Build the cluster and session once at startup, prepare repeated queries, name the local datacenter and set the default consistency to <code>LOCAL_QUORUM</code>. Mark statements <code>idempotent</code> only when running them twice is safe, and only then allow retries or speculative execution. C# with <code>CassandraCSharpDriver</code> 3.22.0 on .NET 10 (run, no TLS or credentials; in 3.22 the local datacenter is set through <code>Policies.NewDefaultLoadBalancingPolicy</code>, and a builder method named <code>WithLocalDatacenter</code> does not exist in that version):</li>

<li><strong>Why:</strong> A prepared statement is parsed once and lets the driver work out which replicas own the partition, so token-aware routing skips an extra hop. A session per request wastes connections, and retrying a non-idempotent write can duplicate it.</li>

<li><strong>How to check:</strong> Connection and request metrics from the driver, and <code>nodetool clientstats</code> or <code>nodetool tpstats</code> on the node for connection counts and queued requests (not run).</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
using Cassandra;

var cluster = Cluster.Builder()
    .AddContactPoints(&quot;127.0.0.1&quot;)
    .WithLoadBalancingPolicy(Policies.NewDefaultLoadBalancingPolicy(&quot;datacenter1&quot;))
    .WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum))
    .Build();
var session = await cluster.ConnectAsync(&quot;bp&quot;); // build once, share as a singleton
var prepared = await session.PrepareAsync(
    &quot;SELECT order_id, status FROM orders_by_customer WHERE customer_id = ?&quot;);
var bound = prepared.Bind(customerId).SetIdempotence(true);
RowSet rows = await session.ExecuteAsync(bound);
</pre></div>


<h3 class="wp-block-heading">13. Turn on authentication, authorization and TLS</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> In <code>cassandra.yaml</code> set <code>authenticator: PasswordAuthenticator</code> and <code>authorizer: CassandraAuthorizer</code> (the <a href="https://cassandra.apache.org/doc/5.0/cassandra/managing/configuration/cass_yaml_file.html" target="_blank" rel="noopener">reference</a> lists both and says the defaults allow everyone), enable <code>server_encryption_options</code> and <code>client_encryption_options</code>, create your own superuser, disable the default <code>cassandra</code> role and give each application a minimal role. Set <code>system_auth</code> replication to 3 to 5 per datacenter, as the security documentation advises, so login still works when a node is down. Not run, because it needs a restart with authentication enabled.</li>

<li><strong>Why:</strong> Authentication proves who is connecting, authorization limits what they can do, and TLS protects traffic between clients and nodes and between nodes.</li>

<li><strong>How to check:</strong> <code>LIST ROLES;</code>, <code>LIST ALL PERMISSIONS OF app_user;</code> after login, and a failed connection test without credentials.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: yaml; title: ; notranslate">
authenticator: PasswordAuthenticator
authorizer: CassandraAuthorizer
role_manager: CassandraRoleManager
</pre></div>


<h2 class="wp-block-heading" id="repair-backup-and-restore-best-practices">Repair, Backup and Restore Best Practices</h2>



<h3 class="wp-block-heading">14. Repair every node inside gc_grace_seconds, in small regular pieces</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> The <a href="https://cassandra.apache.org/doc/5.0/cassandra/managing/operating/repair.html" target="_blank" rel="noopener">repair documentation</a> says incremental repair is the default and suggests, as a starting point, an incremental repair every 1 to 3 days and a full repair every 1 to 3 weeks (or a full repair every 5 days if you avoid incremental). At a minimum, repair must run often enough that the grace period never expires on unrepaired data. Use <code>-pr</code> on each node, and run a full repair after raising a keyspace RF or adding a node. Auto Repair was backported to 5.0.8 and needs <code>-Dcassandra.autorepair.enable=true</code> before the node starts; external schedulers such as Cassandra Reaper are separate projects (not tested here).</li>

<li><strong>Why:</strong> Repair compares replicas with Merkle trees and streams the differences. If a replica missed a delete and the others purge the tombstone after <code>gc_grace_seconds</code>, the old row can return as zombie data.</li>

<li><strong>How to check:</strong> <em>Percent repaired</em> in <code>nodetool tablestats</code> (0.0 on my never-repaired test table), <code>nodetool netstats</code> during a run, and a written schedule that finishes in under 10 days at the default. On a one-replica keyspace <code>nodetool repair -pr bp</code> only reported that no repair is needed, so repair itself was not exercised.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
nodetool repair -pr shop_ks     # primary ranges of this node, then move to the next node
</pre></div>


<h3 class="wp-block-heading">15. Take snapshots, copy them off the node, and test restores</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Schedule <code>nodetool snapshot</code> with retention and copy the files off the node. Restore a copy into a separate cluster on a schedule, time it, and write the time down. The backups documentation describes snapshots as hard links to SSTables and names <code>sstableloader</code> and <code>nodetool refresh</code> as the restore tools. The snapshot command ran here; a full restore was not run.</li>

<li><strong>Why:</strong> A snapshot is cheap, consistent per node and quick, but it lives on the same disk until you move it. Only a restore test proves the files, the schema and your procedure work.</li>

<li><strong>How to check:</strong> List the snapshot directory, compare row counts after a test restore, and note the restore time.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
nodetool snapshot -t daily_2026-11-23 shop_ks
# restore test on a separate cluster: schema first, then
sstableloader -d 10.0.1.11,10.0.1.12 /restore/shop_ks/orders_by_customer
nodetool repair shop_ks
</pre></div>


<h2 class="wp-block-heading" id="operations-monitoring-and-upgrades">Operations, Monitoring and Upgrades</h2>



<h3 class="wp-block-heading">16. Size disks and heap deliberately, and monitor the right signals</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Use a supported Java (11 or 17 on 5.0) and start from the JVM options files shipped with your version. The hardware guide says the heap should be at least 2 GB and no more than 50% of RAM, that with spinning disks the commit log (<code>commitlog_directory</code>) should be on a different physical disk from <code>data_file_directories</code>, and that NFS or SAN for data is an anti-pattern. Keep free disk for compaction, disable swap, and run NTP or chrony because conflicting writes are resolved by timestamp. Alert on the signals below:</li>

<li><strong>Why:</strong> The commit log is written on every write while data files are read by queries, so separate devices stop them competing, and spare disk lets large compactions finish. The signals below are the earliest symptoms of the problems in this guide.</li>

<li><strong>How to check:</strong> <code>df -h</code> on data and commit log paths, GC lines in <code>system.log</code> (the yaml <code>gc_log_threshold</code> logs pauses over 200 ms by default), and the commands in the table. I ran <code>tpstats</code>, <code>tablestats</code> and <code>tablehistograms</code> on the local node.</li>
</ul>



<figure class="wp-block-table"><table><thead><tr><th>Signal</th><th>Where to see it</th><th>What it points to</th></tr></thead><tbody><tr><td>Large partitions</td><td><code>nodetool tablehistograms</code>, <code>tablestats</code></td><td>Unbounded key (practices 2, 3)</td></tr><tr><td>Pending compactions</td><td><code>nodetool compactionstats</code></td><td>Strategy or disk throughput (practice 11)</td></tr><tr><td>Dropped messages, blocked pools</td><td><code>nodetool tpstats</code></td><td>Overloaded node or slow disk</td></tr><tr><td>Tombstone warnings</td><td><code>system.log</code>, <code>tablestats</code></td><td>Deletes and nulls (practice 10)</td></tr><tr><td>Slow queries</td><td><code>TRACING ON</code>, driver latency metrics</td><td>Wide reads, filtering, GC</td></tr><tr><td>Unrepaired data</td><td><em>Percent repaired</em> in <code>tablestats</code></td><td>Repair schedule (practice 14)</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">17. Upgrade with rolling restarts and plan node changes</h3>



<ul class="wp-block-list">
<li><strong>What to do:</strong> Read <code>NEWS.txt</code> for the target version first, snapshot, repair and check health, freeze schema changes, then upgrade one node at a time: <code>nodetool drain</code>, stop, install, start, and wait for <code>UN</code> in <code>nodetool status</code>. Run <code>nodetool upgradesstables</code> only if the notes require it, and move one major version at a time. When you add nodes, bootstrap them and run <code>nodetool cleanup</code> on the old nodes afterwards. The exact procedure was not run here.</li>

<li><strong>Why:</strong> Replication means the cluster serves traffic while one node restarts, provided your consistency level tolerates one node down (practice 7) and repair is up to date.</li>

<li><strong>How to check:</strong> <code>nodetool status</code> and <code>nodetool version</code> on every node, and a rehearsal in staging.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
nodetool snapshot -t pre_upgrade shop_ks
nodetool drain
sudo systemctl stop cassandra
# install the new Cassandra version here
sudo systemctl start cassandra
nodetool status        # wait for UN before the next node
</pre></div>


<span id="common-cassandra-anti-patterns"></span><span id="cassandra-production-readiness-checklist"></span>



<h2 class="wp-block-heading" id="key-takeaways">Key takeaways</h2>



<p class="wp-block-paragraph">Use this as a production checklist. The anti-patterns behind most incidents are the opposites: queue tables with deletes, null writes, <code>ALLOW FILTERING</code>, large cross-partition batches, <code>ALL</code> by default, skipped repair and untested restores.</p>



<ul class="wp-block-list">
<li>Every query reads one partition and none uses <code>ALLOW FILTERING</code>; <code>tablehistograms</code> shows maximum partition size well under 100 MB, and time series use buckets.</li>

<li>Keyspaces use <code>NetworkTopologyStrategy</code> with RF=3 per datacenter; drivers default to <code>LOCAL_QUORUM</code> with the local datacenter set.</li>

<li>Data expires with TTL instead of deletes, every table has a deliberate compaction strategy, and tombstone warnings are monitored.</li>

<li>A repair schedule covers all nodes inside <code>gc_grace_seconds</code>; snapshots are copied off the node and a restore has been timed.</li>

<li>Authentication, authorization and TLS are on, the default superuser is replaced and <code>system_auth</code> is replicated.</li>

<li>A rolling-upgrade runbook has been rehearsed in staging, with alerts for pending compactions, dropped messages and disk use.</li>
</ul>



<p class="wp-block-paragraph">The same query-first thinking appears in the guides for <a href="https://thecodebuzz.com/cosmos-db-best-practices-partitioning/">Cosmos DB partitioning</a>, <a href="https://thecodebuzz.com/neo4j-best-practices-graph-modeling-cypher/">Neo4j graph modeling</a>, <a href="https://thecodebuzz.com/redis-cache-best-practices-development/">Redis caching</a> and <a href="https://thecodebuzz.com/mongodb-schema-design-guidelines-best-practices/">MongoDB schema design</a>.</p>



<p class="wp-block-paragraph">What was not run: anything needing several nodes (consistency behavior, repair, rolling upgrades), TLS and authentication, restore from a snapshot, and the guardrail warnings for batches and partition size. All timings come from one local node and are illustrations, not benchmarks.</p>



<div class="wp-block-group has-background" style="border-radius:8px;background-color:#b6d9ac;padding-top:20px;padding-right:24px;padding-bottom:20px;padding-left:24px"><div class="wp-block-group__inner-container is-layout-constrained wp-container-core-group-is-layout-0d2d72cd wp-block-group-is-layout-constrained">
<p class="wp-block-paragraph" style="font-size:20px"><strong>Found this useful?</strong></p>



<p class="wp-block-paragraph">Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.</p>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noopener">Subscribe to TheCodeBuzz</a></div>
</div>
</div></div>



<h2 class="wp-block-heading" id="faq">FAQ</h2>



<h3 class="wp-block-heading">What are the most important Cassandra best practices?</h3>



<p class="wp-block-paragraph">Model one table per query, choose a high-cardinality partition key and keep partitions under about 100 MB and 100,000 values. Use LOCAL_QUORUM with RF=3 per datacenter, expire data with TTL instead of deleting, repair inside gc_grace_seconds and test your restores.</p>



<h3 class="wp-block-heading">What is the ideal partition size in Cassandra?</h3>



<p class="wp-block-paragraph">The official data modeling guide suggests below about 100,000 values and below 100 MB per partition, with a hard limit of 2 billion cells. Check real sizes with nodetool tablehistograms and the compacted partition maximum bytes in nodetool tablestats, and add a time bucket to the partition key if a partition keeps growing.</p>



<h3 class="wp-block-heading">Which Cassandra consistency level should I use?</h3>



<p class="wp-block-paragraph">For multi-datacenter production use LOCAL_QUORUM for reads and writes with RF=3 per datacenter. A quorum is n/2 + 1 replicas, so 2 reads plus 2 writes exceed RF=3 and every read overlaps the latest write, without waiting on another datacenter.</p>



<h2 class="wp-block-heading" id="sources">Sources and further reading</h2>



<ul class="wp-block-list">
<li><a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/data-modeling/intro.html" target="_blank" rel="noopener">Data modeling introduction (Apache Cassandra documentation)</a></li>

<li><a href="https://cassandra.apache.org/doc/5.0/cassandra/developing/cql/dml.html" target="_blank" rel="noopener">Data manipulation: SELECT, batches, ALLOW FILTERING (Apache Cassandra documentation)</a></li>

<li><a href="https://cassandra.apache.org/doc/5.0/cassandra/managing/configuration/cass_yaml_file.html" target="_blank" rel="noopener">cassandra.yaml configuration reference (Apache Cassandra documentation)</a></li>

<li><a href="https://cassandra.apache.org/doc/5.0/cassandra/managing/operating/repair.html" target="_blank" rel="noopener">Repair (Apache Cassandra documentation)</a></li>
</ul>



<script type="application/ld+json">{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "What are the most important Cassandra best practices?", "acceptedAnswer": {"@type": "Answer", "text": "Model one table per query, choose a high-cardinality partition key and keep partitions under about 100 MB and 100,000 values. Use LOCAL_QUORUM with RF=3 per datacenter, expire data with TTL instead of deleting, repair inside gc_grace_seconds and test your restores."}}, {"@type": "Question", "name": "What is the ideal partition size in Cassandra?", "acceptedAnswer": {"@type": "Answer", "text": "The official data modeling guide suggests below about 100,000 values and below 100 MB per partition, with a hard limit of 2 billion cells. Check real sizes with nodetool tablehistograms and the compacted partition maximum bytes in nodetool tablestats, and add a time bucket to the partition key if a partition keeps growing."}}, {"@type": "Question", "name": "Which Cassandra consistency level should I use?", "acceptedAnswer": {"@type": "Answer", "text": "For multi-datacenter production use LOCAL_QUORUM for reads and writes with RF=3 per datacenter. A quorum is n/2 + 1 replicas, so 2 reads plus 2 writes exceed RF=3 and every read overlaps the latest write, without waiting on another datacenter."}}]}</script><p>The post <a href="https://thecodebuzz.com/cassandra-best-practices-guidelines/">Cassandra Best Practices: 17 Rules for Data and Ops</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/cassandra-best-practices-guidelines/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
