<?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>TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Thu, 03 Dec 2026 21:40:32 +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>TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Neo4j Best Practices: Graph Modeling and Cypher Performance</title>
		<link>https://thecodebuzz.com/neo4j-best-practices-graph-modeling/</link>
					<comments>https://thecodebuzz.com/neo4j-best-practices-graph-modeling/#respond</comments>
		
		<dc:creator><![CDATA[Izzy]]></dc:creator>
		<pubDate>Thu, 03 Dec 2026 18:47:07 +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[Query Tuning]]></category>
		<guid isPermaLink="false">https://thecodebuzz.com/?p=31178</guid>

					<description><![CDATA[<p>Neo4j best practices for graph modeling, indexes, constraints and Cypher tuning with EXPLAIN and PROFILE, plus batching, security and upgrades.</p>
<p>The post <a href="https://thecodebuzz.com/neo4j-best-practices-graph-modeling/">Neo4j Best Practices: Graph Modeling and Cypher Performance</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<p>This guide covers the Neo4j best practices for graph modeling and Cypher performance that apply to a production database. Neo4j is a graph database that stores nodes, relationships and properties, and you query it with Cypher. A graph that works on a laptop with a few hundred nodes can behave very differently once real traffic and real data volumes arrive.</p>
<p>It&#8217;s written for software engineers, architects and DBAs who run Neo4j in production. We will cover data modeling, supernodes, indexes and constraints, reading EXPLAIN and PROFILE, batching writes, security, operations and upgrades. Each rule comes with its reason, so you can decide when it applies to your workload.</p>
<p>Neo4j now ships calendar-versioned monthly releases alongside the 5.26 LTS line. Many older guides are dated. Before we start, make sure you have a running instance and a small sample dataset to try the queries on.</p>
<blockquote>
<p><strong>Version note:</strong> This guide targets Neo4j 2026.10.2 (the current monthly release) and the 5.26.33 LTS line, both released on 6 November 2026.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><strong>In this guide</strong></p>
</blockquote>
<ul>
<li><a href="#neo4j-best-practices-at-a-glance">Neo4j Best Practices at a Glance</a></li>
<li><a href="#graph-data-modeling-best-practices-nodes-relationships-and-s">Graph Data Modeling Best Practices: Nodes, Relationships and Supernodes</a></li>
<li><a href="#neo4j-indexes-and-constraints-which-type-to-use">Neo4j Indexes and Constraints: Which Type to Use</a></li>
<li><a href="#cypher-query-optimization-read-explain-and-profile-then-tune">Cypher Query Optimization: Read EXPLAIN and PROFILE, Then Tune</a></li>
<li><a href="#transactions-batching-drivers-security-and-operations-in-pro">Transactions, Batching, Drivers, Security and Operations in Production</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>
<h2 id="neo4j-best-practices-at-a-glance">Neo4j Best Practices at a Glance</h2>
<p>Write down your queries first and model the graph for them. Then index and constrain the lookup properties, profile every important query, batch your writes and test upgrades on staging before production.</p>
<p>The table below summarises the rules for Neo4j graph data modeling, Cypher query optimization and day-to-day operations. Each rule is explained in the sections that follow.</p>
<blockquote>
<p><strong>Note: </strong> A graph database stores things as nodes and the links between them as relationships, much like a city map with places and the roads that join them. Good Neo4j performance tuning mostly means making sure a query can start at the right place on the map and only walk the roads it needs.</p>
</blockquote>
<p>Here is a quick reference of the main areas, what to do and what to avoid:</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>List your questions first, then shape nodes and relationships around them.</td>
<td>Copying a relational schema table by table.</td>
</tr>
<tr>
<td><strong>Naming</strong></td>
<td>Use CamelCase labels, UPPER_SNAKE_CASE relationship types, camelCase property keys.</td>
<td>Mixed styles and one generic <code>RELATED_TO</code> for everything.</td>
</tr>
<tr>
<td><strong>Identifiers</strong></td>
<td>Give every node a uniquely identifying property and enforce it with a uniqueness constraint.</td>
<td>Relying on MERGE alone with no constraint.</td>
</tr>
<tr>
<td><strong>Indexes</strong></td>
<td>Use range indexes for most filters and keep token lookup indexes.</td>
<td>Dropping token lookup indexes.</td>
</tr>
<tr>
<td><strong>Query shape</strong></td>
<td>Filter early and return only the properties you need.</td>
<td>Returning whole nodes and relationships.</td>
</tr>
<tr>
<td><strong>Parameters</strong></td>
<td>Pass values as parameters such as <code>$customerId</code>.</td>
<td>String literals built into the query text.</td>
</tr>
<tr>
<td><strong>Variable-length paths</strong></td>
<td>Set an upper bound, e.g. <code>[:KNOWS*1..3]</code>.</td>
<td>Open-ended <code>[*]</code> patterns.</td>
</tr>
<tr>
<td><strong>Writes</strong></td>
<td>Batch with <code>UNWIND</code> and <code>CALL { } IN TRANSACTIONS</code>.</td>
<td>One giant write transaction.</td>
</tr>
<tr>
<td><strong>Security</strong></td>
<td>Use role-based access with least privilege.</td>
<td>Putting the admin account in application config.</td>
</tr>
<tr>
<td><strong>Upgrades</strong></td>
<td>Rehearse on staging with your real queries.</td>
<td>Upgrading straight to production.</td>
</tr>
<tr>
<td><strong>Monitoring and backups</strong></td>
<td>Watch slow queries and restore backups into a test environment on a schedule.</td>
<td>Taking backups that are never restored.</td>
</tr>
</tbody>
</table>
</figure>
<h3>Which Neo4j and Cypher versions does this guide cover?</h3>
<p>The current monthly release is <strong>2026.10.2</strong> and the 5.x LTS line is at <strong>5.26.33</strong>, both released on 6 November 2026. The Cypher manual is documented for versions 5 and 25, so check which one your server runs before copying syntax from the docs.</p>
<h2 id="graph-data-modeling-best-practices-nodes-relationships-and-s">Graph Data Modeling Best Practices: Nodes, Relationships and Supernodes</h2>
<p>Write down the questions your application must answer first, then let them shape the model. Use a <strong>node</strong> for something you identify and traverse to, a <strong>relationship</strong> for a verb that connects two things, and a <strong>property</strong> for a simple value you only read or filter on.</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 graph model is like a city map. Nodes are the places (a shop, a station), and relationships are the roads between them. A property is a detail written on a place, such as its opening hours. You don&#8217;t drive to opening hours, so they don&#8217;t need to be a place of their own.</p>
</blockquote>
<h3>How do you choose between a node, a relationship and a property?</h3>
<p>Ask what each query does with the value. If it only reads or filters on it, keep it as a property. If queries move through it, make it a node.</p>
<p>A date is a good example. If queries filter by date range, a date node can serve better than a property on every order. Load sample data and test both versions, because the model can change as your priorities change.</p>
<h3>Which naming and identity rules should you follow?</h3>
<p>Follow the conventions from the official Neo4j tutorial so your queries stay readable and predictable:</p>
<ul>
<li><strong>Labels:</strong> use CamelCase, e.g. <code>Person</code>, <code>Movie</code>.</li>
<li><strong>Relationship types:</strong> use UPPER_SNAKE_CASE, e.g. <code>ACTED_IN</code>. Make them specific so the database traverses only the relevant connections, not one generic <code>RELATED_TO</code>.</li>
<li><strong>Property keys:</strong> use camelCase, e.g. <code>orderedAt</code>.</li>
<li><strong>Identity:</strong> give every node a property, or set of properties, that uniquely identifies it.</li>
<li><strong>Size:</strong> relationships take up space, so keep their count down. Complex data is often better split across a few nodes than put in one huge node or many tiny ones.</li>
</ul>
<h3>What is the Neo4j supernode problem?</h3>
<p>A <strong>supernode</strong> (dense node) is a node with a very large number of relationships, such as a <code>Country</code> or a popular <code>Product</code>. Expanding it touches every one of those relationships, so any query that passes through it gets slow.</p>
<p>Take a retail example. If every order points directly at its product, a query for last month&#8217;s orders still has to walk all orders ever placed. The fix is to split the hub into time buckets: <code>Product</code> to <code>MonthBucket</code> to <code>Order</code>. The animated diagram below shows the same query before and after the remodel.</p>
<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/neo4j-best-practices-graph-modeling-diagram-2.gif" alt="Before and after Neo4j model: a Product hub scans every order, then month buckets let the query touch only the 2026-10 bucket." width="1200" height="675" />
<figcaption>Splitting the Product hub into per-month buckets lets the same query expand one bucket instead of every order ever placed.</figcaption>
</figure>
<p>The Cypher below creates the before model, then the after model:</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-text">// Before: every order hangs directly off the product hub
MERGE (p:Product {sku: $sku})
CREATE (o:Order {orderId: $orderId, orderedAt: date($orderedAt)})
CREATE (o)-[:CONTAINS]-&gt;(p);

// After: orders attach to a per-product month bucket
MERGE (p:Product {sku: $sku})
MERGE (b:MonthBucket {productSku: $sku, month: $month})
MERGE (p)-[:HAS_BUCKET]-&gt;(b)
CREATE (o:Order {orderId: $orderId, orderedAt: date($orderedAt)})
CREATE (b)-[:HAS_ORDER]-&gt;(o);</code></pre>
<p>Both versions use parameters, and the bucket is keyed by product and month. Now compare the read side:</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-text">// Before: expands every order on the product, then filters
PROFILE
MATCH (:Product {sku: $sku})&lt;-[:CONTAINS]-(o:Order)
WHERE o.orderedAt &gt;= date($from) AND o.orderedAt &lt; date($to)
RETURN o.orderId;

// After: expands only one bucket
PROFILE
MATCH (:Product {sku: $sku})-[:HAS_BUCKET]-&gt;(:MonthBucket {month: $month})-[:HAS_ORDER]-&gt;(o:Order)
RETURN o.orderId;</code></pre>
<p>Run both with <code>PROFILE</code> on your own data and compare the <strong>db hits</strong> reported by the expand operators. The bucketed query should touch far fewer relationships. Use the typed relationship plus a filter on the other end, and don&#8217;t route traversals through the hub when a property can answer the question.</p>
<h2 id="neo4j-indexes-and-constraints-which-type-to-use">Neo4j Indexes and Constraints: Which Type to Use</h2>
<p>Create <strong>uniqueness constraints</strong> on business identifiers and a <strong>range index</strong> for most filters. Add text, point, full-text or vector indexes only for the specific predicates they solve. This is the core of Neo4j indexes and constraints, and it keeps writes cheap and lookups fast.</p>
<h3>What index types does Neo4j offer?</h3>
<p>The current Cypher manual splits indexes into two groups. <strong>Performance indexes</strong> (range, text, point and token lookup) are picked automatically by the planner. <strong>Search indexes</strong> (full-text and vector) are never picked automatically, so you must query them explicitly.</p>
<p>The old B-tree index type was replaced by range, point and text indexes. If a guide still tells you to create a B-tree index, it is dated.</p>
<blockquote>
<p><strong>Note: </strong> An index works like the index at the back of a book. Instead of reading every page to find a topic, you look it up and jump straight to the right page. The difference is that the database keeps its index up to date on every write, which is why you should not index everything.</p>
</blockquote>
<p>The table below compares the six types.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Index type</th>
<th>Best for</th>
<th>Limits</th>
<th>How it is used</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Range</strong></td>
<td>Most predicates (equality, ranges, ordering)</td>
<td>Single or composite property</td>
<td>Default when <code>CREATE INDEX</code> has no type; planner chooses it</td>
</tr>
<tr>
<td><strong>Text</strong></td>
<td><code>CONTAINS</code>, <code>ENDS WITH</code>, strings over 8 kb</td>
<td>Single property</td>
<td>Planner chooses it</td>
</tr>
<tr>
<td><strong>Point</strong></td>
<td>Spatial predicates</td>
<td>Single property</td>
<td>Planner chooses it</td>
</tr>
<tr>
<td><strong>Token lookup</strong></td>
<td>Label and relationship type predicates</td>
<td>Solves nothing else</td>
<td>Planner chooses it</td>
</tr>
<tr>
<td><strong>Full-text</strong></td>
<td>Relevance search on text</td>
<td>Search index</td>
<td>Explicit procedure call</td>
</tr>
<tr>
<td><strong>Vector</strong></td>
<td>Similarity search</td>
<td>Search index</td>
<td><code>db.index.vector.queryNodes()</code>; from Neo4j 2025.10 the query argument can also be a <code>VECTOR</code> value</td>
</tr>
</tbody>
</table>
</figure>
<p>The animated diagram below walks through which index the planner reaches for, one predicate at a time.</p>
<figure class="wp-block-image size-full"><img decoding="async" src="https://thecodebuzz.com/wp-content/uploads/2026/11/neo4j-best-practices-graph-modeling-diagram-3.gif" alt="Decision tree: string predicates go to a text index for CONTAINS or ENDS WITH, else range; label-only goes to token lookup; similarity goes to search indexes." width="1200" height="675" />
<figcaption>Performance indexes are chosen by the planner; full-text and vector indexes are never chosen automatically and must be called explicitly.</figcaption>
</figure>
<h3>Does a text index replace the range index?</h3>
<p>No. When both exist on one string property, the planner uses the text index only for <code>CONTAINS</code> and <code>ENDS WITH</code>, or when stored strings exceed 8 kb. Every other predicate uses the range index, so keep both if you need both.</p>
<p>Never drop the token lookup indexes. They solve label and relationship type predicates, and removing them hurts query performance.</p>
<h3>How do you create a uniqueness constraint and a supporting index?</h3>
<p>A uniqueness constraint allows only one node per identifier value, and it backs lookups with an index. In a finance model, <code>Account.accountNumber</code> is unique, and <code>Transaction</code> gets a composite range index on <code>(accountId, postedAt)</code>.</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-sql">CREATE CONSTRAINT account_number_unique IF NOT EXISTS
FOR (a:Account) REQUIRE a.accountNumber IS UNIQUE;

CREATE INDEX txn_account_posted IF NOT EXISTS
FOR (t:Transaction) ON (t.accountId, t.postedAt);

MERGE (a:Account {accountNumber: $accountNumber})
SET a.ownerName = $ownerName, a.status = $status;</code></pre>
<p>The <code>MERGE</code> uses only the unique key, and <code>SET</code> writes the other properties.</p>
<ul>
<li><strong>Use CREATE:</strong> when you know the node is new, for example a fresh transaction with a generated ID.</li>
<li><strong>Use MERGE:</strong> when the node may already exist. Merge on the constrained key only, so you never create near-duplicates.</li>
</ul>
<h2 id="cypher-query-optimization-read-explain-and-profile-then-tune">Cypher Query Optimization: Read EXPLAIN and PROFILE, Then Tune</h2>
<p><strong>EXPLAIN</strong> shows the planned operators without running the query. <strong>PROFILE</strong> runs the query and reports rows and db hits (units of storage work) for each operator. Use EXPLAIN to check a plan safely, and PROFILE to find where the work really goes.</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 query plan is like a route on a map. EXPLAIN shows the route before you drive. PROFILE records the real trip, with the distance of each leg. Unlike a map, PROFILE actually executes the query, so be careful with write queries.</p>
</blockquote>
<p>The animated diagram below shows the tuning loop: run EXPLAIN, run PROFILE, spot the problem operator, apply a fix, then PROFILE again and compare db hits.</p>
<h3>How do you find the slow part of a query?</h3>
<p>Here&#8217;s a simplified healthcare query that finds the providers connected to one patient. It has a function on the lookup property, an open-ended path and whole nodes in the result:</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-sql">PROFILE
MATCH (p:Patient)-[*]-(pr:Provider)
WHERE toLower(p.patientId) = 'p-1001'
RETURN p, pr</code></pre>
<p>In the PROFILE output you would typically see a <code>NodeByLabelScan</code> on <code>Patient</code>, because the function stops the index from being used. The row count then stays high through the expand and filter steps. Compare the db hits of each operator to see which one costs the most.</p>
<p>These are the operators to look for:</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Operator or sign</th>
<th>What it means</th>
<th>Usual fix</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>AllNodesScan / NodeByLabelScan</strong></td>
<td>Reads every node (of the label) on a big dataset</td>
<td>Add an index or constraint, remove functions from the predicate</td>
</tr>
<tr>
<td><strong>Eager</strong></td>
<td>Reads all input before continuing, which raises memory use</td>
<td>Restructure the query, split reads from writes</td>
</tr>
<tr>
<td><strong>High row count</strong></td>
<td>Filter is applied too late</td>
<td>Move the filter earlier</td>
</tr>
</tbody>
</table>
</figure>
<p>The fixed version looks up the patient by an indexed key, names the relationship types, bounds the path and returns only needed properties:</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-sql">PROFILE
MATCH (p:Patient {patientId: $patientId})-[:TREATED_BY|REFERRED_TO*1..3]-(pr:Provider)
RETURN DISTINCT pr.providerId, pr.name</code></pre>
<p>The plan should now start with a <code>NodeUniqueIndexSeek</code> or <code>NodeIndexSeek</code> (this assumes a constraint or index on <code>Patient.patientId</code>). It then expands a few hops with a small row count, and the db hits should be lower than before.</p>
<h3>What are the Neo4j query tuning steps?</h3>
<ol>
<li><strong>Filter early:</strong> Apply predicates as soon as possible, so later stages handle fewer rows.</li>
<li><strong>Return only what you need:</strong> Return properties, not whole nodes and relationships.</li>
<li><strong>Name labels and relationship types:</strong> Explicit names give the planner better statistics.</li>
<li><strong>Bound variable-length paths:</strong> Use an upper limit, e.g. <code>[:KNOWS*1..3]</code>.</li>
<li><strong>Use parameters:</strong> Cypher can reuse the cached plan and skip planning again.</li>
<li><strong>Re-run PROFILE:</strong> Compare db hits with your first run.</li>
</ol>
<p>This example combines a parameter and a bounded path:</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-sql">MATCH (c:Customer {customerId: $customerId})-[:KNOWS*1..3]-(f:Customer)
RETURN DISTINCT f.customerId, f.name
LIMIT 25</code></pre>
<p>The Python snippet below passes the parameter as a dictionary with the official <code>neo4j</code> driver:</p>
<p class="code-label"><strong>PYTHON</strong></p>
<pre><code class="language-python">from neo4j import GraphDatabase

query = """
MATCH (c:Customer {customerId: $customerId})-[:KNOWS*1..3]-(f:Customer)
RETURN DISTINCT f.customerId AS id, f.name AS name
LIMIT 25
"""

with GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "password")) as driver:
    records, summary, keys = driver.execute_query(
        query,
        parameters_={"customerId": "C-1001"},
        database_="neo4j",
    )
    for record in records:
        print(record["id"], record["name"])</code></pre>
<p>Both Cypher 5 and Cypher 25 are documented in the manual, so read the version that matches your server. Plan operator names and planner behaviour can differ between versions.</p>
<h2 id="transactions-batching-drivers-security-and-operations-in-pro">Transactions, Batching, Drivers, Security and Operations in Production</h2>
<p>Batch writes with <code>UNWIND</code> and <code>CALL { } IN TRANSACTIONS</code>, keep transactions short, reuse one driver per application, grant least-privilege roles, and test every upgrade on staging. The sections below cover each of these for Neo4j performance tuning in production.</p>
<h3>How Do You Batch Writes in Cypher?</h3>
<p>Send many rows as one parameter and let <code>UNWIND</code> expand them. This saves a network round trip per row.</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-text">UNWIND $rows AS row
MERGE (o:Order {orderId: row.orderId})
SET o.total = row.total;</code></pre>
<p>For large loads, commit in chunks. The next query reads a CSV file and commits every 10,000 rows.</p>
<p class="code-label"><strong>CYPHER</strong></p>
<pre><code class="language-text">LOAD CSV WITH HEADERS FROM 'file:///orders.csv' AS row
CALL (row) {
  MERGE (o:Order {orderId: row.orderId})
  SET o.total = toFloat(row.total)
} IN TRANSACTIONS OF 10000 ROWS;</code></pre>
<p><code>IN TRANSACTIONS</code> must run in an auto-commit (implicit) transaction, so don&#8217;t wrap it in an explicit <code>BEGIN</code>.</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 transaction is a group of changes that succeed or fail together. Think of a shop till: you can ring up one huge basket and block the queue, or process it in smaller bags so each one is finished and paid for. Batches work the same way, although a failed batch only rolls back itself, not the ones already committed.</p>
</blockquote>
<p>One huge transaction holds memory and locks until it ends. Batches commit progress and release resources as they go.</p>
<h3>How Do You Avoid Lock Contention and Deadlocks?</h3>
<p><code>MERGE</code> and relationship creation lock the nodes involved. If two bulk writers touch the same hub (supernode), they can block each other or deadlock.</p>
<ul>
<li><strong>Partition the input:</strong> give each writer a separate slice of keys.</li>
<li><strong>Sort by key:</strong> every writer then takes locks in the same order.</li>
<li><strong>Serialise hub writers:</strong> run one writer at a time for data that attaches to a supernode.</li>
<li><strong>Retry transient errors:</strong> let the client retry a deadlock instead of failing the whole load.</li>
</ul>
<h3>How Should You Manage Drivers and Connections?</h3>
<p>Create one driver object per application and share it. The driver holds the connection pool, so building one per request wastes connections.</p>
<p>Use managed transaction functions or <code>ExecuteQueryAsync</code>, because the driver retries transient failures for you. Open sessions only for short work.</p>
<p class="code-label"><strong>C#</strong></p>
<pre><code class="language-csharp">using Neo4j.Driver;

await using var driver = GraphDatabase.Driver(
    "neo4j://db.example.com:7687",
    AuthTokens.Basic(
        Environment.GetEnvironmentVariable("NEO4J_USER"),
        Environment.GetEnvironmentVariable("NEO4J_PASSWORD")));

var result = await driver.ExecuteQueryAsync(
    "MATCH (c:Customer {customerId: $customerId})-[:PLACED]-&gt;(o:Order) RETURN o.orderId AS orderId",
    new { customerId = "C-1001" },
    config =&gt; config.WithDatabase("neo4j"));

foreach (var record in result.Result)
{
    Console.WriteLine(record["orderId"].As&lt;string&gt;());
}</code></pre>
<p>This reads credentials from the environment and passes the customer id as a parameter.</p>
<h3>How Do You Secure a Neo4j Database?</h3>
<p>Never concatenate user input into Cypher. Parameters stop Cypher injection and also let the plan be reused.</p>
<p>Use role-based access control and give each application only the privileges it needs, such as read-only for reporting services. Keep the admin account out of application config.</p>
<h3>What Does Production Operations Need?</h3>
<p>Run a cluster, so the failure of one server does not stop writes. Connect with a routing URI (<code>neo4j://</code>) so the driver finds the current writer.</p>
<p>Size memory on purpose. The <strong>page cache</strong> holds graph data in memory, and the heap holds query working data. Watch page cache hit ratio, slow queries and transaction counts.</p>
<p>Take regular backups, and restore one into a test environment on a schedule. A backup you have never restored is unproven.</p>
<h3>How Should You Plan Neo4j Upgrades?</h3>
<p>Test every upgrade on staging with your real queries. Neo4j ships calendar-versioned monthly releases (2026.10.2 is current, from 6 November 2026), with hotfixes until the next release. The 5.26 LTS line is at 5.26.33.</p>
<p>Recent releases had query-affecting bugs. 2026.08.0 could make some queries fail (2026.08.1 was recommended), and 2026.07.0 had a problem with <code>trim()</code>. Neo4j Ops Manager 1.15.0 and later needs Neo4j persistence on 5.26 LTS or newer. Drivers 6.x, 5.x and 4.4 are listed as compatible.</p>
<p>This table compares the two release tracks for upgrade planning.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Track</th>
<th>Cadence</th>
<th>Suits</th>
<th>What to test</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Monthly release</strong></td>
<td>Calendar-versioned, hotfixes until the next release</td>
<td>Teams that can rehearse upgrades often</td>
<td>Key queries, <code>trim()</code> and other functions, driver compatibility</td>
</tr>
<tr>
<td><strong>5.26 LTS</strong></td>
<td>Patch releases on the 5.x line</td>
<td>Teams that want fewer changes</td>
<td>Query results, Ops Manager persistence, driver version</td>
</tr>
</tbody>
</table>
</figure>
<h2 id="common-anti-patterns-and-production-readiness-checklist">Common Anti-Patterns and Production Readiness Checklist</h2>
<p>Most slow or fragile Neo4j systems share the same few mistakes, and each one has a simple fix. Use this section as a review list for Neo4j performance tuning before you go live.</p>
<h3>Which Neo4j anti-patterns cause the most trouble?</h3>
<p>The table below lists nine common anti-patterns, the symptom you will see, and the fix.</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>One generic relationship type for everything</strong></td>
<td>Slow traversals, unclear queries</td>
<td>Use specific types (e.g. <code>PLACED</code>, <code>CONTAINS</code>)</td>
</tr>
<tr>
<td><strong>No uniqueness constraint</strong></td>
<td>Duplicate nodes from <code>MERGE</code></td>
<td>Add a constraint on the business key</td>
</tr>
<tr>
<td><strong>String literals in queries</strong></td>
<td>Plan cache churn</td>
<td>Use parameters</td>
</tr>
<tr>
<td><strong>Unbounded <code>[*]</code> paths</strong></td>
<td>Memory spikes, long runtimes</td>
<td>Set an upper bound, e.g. <code>[*1..3]</code></td>
</tr>
<tr>
<td><strong>Supernode in the path</strong></td>
<td>Slow expansions</td>
<td>Bucket the hub or filter before expanding</td>
</tr>
<tr>
<td><strong>Dropping the token lookup index</strong></td>
<td>Slow label scans</td>
<td>Recreate it</td>
</tr>
<tr>
<td><strong>Returning whole nodes</strong></td>
<td>Large payloads</td>
<td>Return only the properties you need</td>
</tr>
<tr>
<td><strong>One giant write transaction</strong></td>
<td>Memory pressure, long locks</td>
<td>Batch with <code>CALL { } IN TRANSACTIONS</code></td>
</tr>
<tr>
<td><strong>Upgrading straight to production</strong></td>
<td>Query failures from release bugs</td>
<td>Test on staging first</td>
</tr>
</tbody>
</table>
</figure>
<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 plan cache is like a kitchen&#8217;s recipe card box. If every query arrives with its values baked into the text, the database sees a new recipe each time and writes a fresh card. With parameters, the recipe stays the same and only the ingredients change.</p>
</blockquote>
<h3>What should you check before going live?</h3>
<p>Work through this ordered checklist for your graph database modeling and operations, and sign off each item before launch.</p>
<ol>
<li><strong>Queries written down:</strong> list the questions first and model the graph for them.</li>
<li><strong>Naming conventions applied:</strong> CamelCase labels, UPPER_SNAKE_CASE relationship types, camelCase property keys.</li>
<li><strong>Uniqueness constraints in place:</strong> one for every business identifier you <code>MERGE</code> on.</li>
<li><strong>Indexes match predicates:</strong> keep the token lookup indexes.</li>
<li><strong>Key queries profiled:</strong> run <code>PROFILE</code> and record db hits as your baseline.</li>
<li><strong>Parameters everywhere:</strong> no user input concatenated into Cypher.</li>
<li><strong>Variable-length paths bounded:</strong> every pattern has an upper limit.</li>
<li><strong>Bulk loads batched:</strong> use <code>UNWIND</code> with <code>IN TRANSACTIONS</code>.</li>
<li><strong>Roles and least privilege configured:</strong> keep the admin account out of application config.</li>
<li><strong>Backups restored in a test:</strong> prove the restore works, not only the backup.</li>
<li><strong>Upgrade rehearsed on staging:</strong> run your real queries against the target release.</li>
</ol>
<h2 id="key-takeaways">Key takeaways</h2>
<p>These are the highest-impact rules from this guide:</p>
<ul>
<li><strong>Model for your queries:</strong> Write down the questions first. Use nodes for things you traverse to, specific relationship types for verbs, and properties for simple values you only read or filter on.</li>
<li><strong>Constrain identifiers:</strong> Add a uniqueness constraint on each business key, and MERGE on that key only. This prevents duplicate nodes and gives MERGE an index-backed lookup.</li>
<li><strong>Pick the right index:</strong> Use a range index for most filters. Add a text index only for CONTAINS and ENDS WITH, and use point, full-text or vector indexes for their specific predicates. Never drop the token lookup indexes.</li>
<li><strong>Profile with PROFILE:</strong> Use EXPLAIN to check the plan safely, then PROFILE to find the operators with the most db hits. Watch for label scans, Eager operators and row counts that stay high.</li>
<li><strong>Parameterize every query:</strong> Pass values as parameters, never string literals. This lets Cypher reuse the plan and keeps user input out of the query text.</li>
<li><strong>Bound your paths:</strong> Set an upper limit on variable-length patterns, for example <code>[:KNOWS*1..3]</code>, and keep traversals away from supernodes by bucketing or filtering.</li>
<li><strong>Batch your writes:</strong> Use UNWIND with <code>CALL { } IN TRANSACTIONS</code> and keep transactions short. Reuse one driver per application, and use a routing URI in a cluster.</li>
<li><strong>Rehearse upgrades:</strong> Test every monthly release or 5.26 LTS update on staging with your real queries. Restore your backups into a test environment on a schedule to prove they work.</li>
</ul>
<p>That&#8217;s all! Happy coding!</p>
<p>Did this guide help you with your Neo4j modeling or Cypher performance issue? Please share your questions or experience in the comments below.</p>
<p>Bookmark this page and share it with your team, so it is handy for your next production review. Subscribe to TheCodeBuzz for more database best-practice guides.</p>
<h2 id="faq">FAQ</h2>
<h3><strong>How should I model data in Neo4j: node, relationship or property?</strong></h3>
<p>Write down your queries first and let them decide. Use a node for something you identify and traverse to, a relationship for a verb that connects two things, and a property for a simple value you only read or filter on. If queries filter by date range, for example, a date can work better as its own node than as a property. Load sample data and test, because the model can change as your priorities change.</p>
<h3><strong>How do I speed up a slow Cypher query?</strong></h3>
<p>Run PROFILE and look at the db hits and row counts for each operator to find where the work goes. Then filter as early as possible, return only the properties you need, and make sure an index backs the lookup property. Use parameters instead of literals so the plan can be reused, and set an upper bound on variable-length paths (e.g. <code>[:KNOWS*1..3]</code>). Run PROFILE again and compare db hits to confirm the change helped.</p>
<h3><strong>How do I avoid supernodes (dense nodes) in Neo4j?</strong></h3>
<p>Split the hub so queries do not have to expand every relationship on it. A common way is to bucket by time (e.g. Product, then a Month bucket, then Order), so a query for one month only expands that bucket. Use specific relationship types so only the relevant connections are traversed. Avoid routing traversals through the hub when a property can answer the question.</p>
<h3><strong>Which Neo4j index type should I use: range, text, point, full-text or vector?</strong></h3>
<p>Use a range index for most filters. It is the default when <code>CREATE INDEX</code> has no type, and it supports single or composite properties. Add a text index only for <code>CONTAINS</code> and <code>ENDS WITH</code> on strings, a point index for spatial data, and full-text or vector indexes when you need search. The last two must be queried explicitly. Keep the token lookup indexes, because they solve label and relationship type predicates.</p>
<h3><strong>What is the difference between EXPLAIN and PROFILE in Cypher?</strong></h3>
<p>EXPLAIN shows the planned operators without running the query, so it is safe for checking a plan. PROFILE runs the query and reports rows and db hits for each operator, so it shows where the real work happens. Use EXPLAIN to check the plan, then PROFILE to measure and compare before and after a change.</p>
<h2 id="sources">Sources and further reading</h2>
<ul>
<li><a href="https://neo4j.com/release-notes/database/" target="_blank" rel="noopener">Neo4j Release Notes Archive: Database</a> (Neo4j)</li>
<li><a href="https://neo4j.com/developer/kb/neo4j-supported-versions/" target="_blank" rel="noopener">Neo4j Supported Versions</a> (Neo4j)</li>
<li><a href="https://neo4j.com/docs/cypher-manual/25/planning-and-tuning/query-tuning/" target="_blank" rel="noopener">Query tuning &#8211; Cypher Manual (25)</a> (Neo4j)</li>
<li><a href="https://neo4j.com/docs/cypher-manual/current/indexes/performance-indexes/using-indexes/" target="_blank" rel="noopener">The impact of indexes on query performance &#8211; Cypher Manual</a> (Neo4j)</li>
<li><a href="https://neo4j.com/docs/cypher-manual/current/indexes/" target="_blank" rel="noopener">Indexes &#8211; Cypher Manual</a> (Neo4j)</li>
</ul>
<p>&nbsp;</p>


<p class="wp-block-paragraph"></p><p>The post <a href="https://thecodebuzz.com/neo4j-best-practices-graph-modeling/">Neo4j Best Practices: Graph Modeling and Cypher Performance</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/neo4j-best-practices-graph-modeling/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>SQLite Best Practices: WAL, PRAGMA, Backups, Locking</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: the PRAGMA settings to change, WAL mode, fixing 'database is locked', safe online backups and when to move on.</p>
<p>The post <a href="https://thecodebuzz.com/sqlite-best-practices-production/">SQLite Best Practices: WAL, PRAGMA, Backups, Locking</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 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 loading="lazy" 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: WAL, PRAGMA, Backups, Locking</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 loading="lazy" 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: Modeling, Indexes and Cypher Tuning</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 for slow queries: model around your questions, add constraints and indexes, read PROFILE db hits and batch writes. 18 rules, tested.</p>
<p>The post <a href="https://thecodebuzz.com/neo4j-best-practices-graph-modeling-cypher/">Neo4j Best Practices: Modeling, Indexes and Cypher Tuning</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; 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; 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; 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; 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; 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; 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; 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; 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; 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: Modeling, Indexes and Cypher Tuning</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>
	</channel>
</rss>
