<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Oscar Flávio Jr — Writing</title>
    <link>https://oscarflaviojr.com/writing/</link>
    <atom:link href="https://oscarflaviojr.com/feed.xml" rel="self" type="application/rss+xml"/>
    <description>Technical writing on software engineering, AI engineering and product engineering by Oscar Flávio Jr.</description>
    <language>en</language>
    <lastBuildDate>Mon, 30 Nov 2026 12:00:00 GMT</lastBuildDate>
    <item>
      <title>Local RAG with Ollama: how retrieval-augmented generation works</title>
      <link>https://oscarflaviojr.com/writing/local-rag-with-ollama.html</link>
      <guid isPermaLink="true">https://oscarflaviojr.com/writing/local-rag-with-ollama.html</guid>
      <pubDate>Mon, 30 Nov 2026 12:00:00 GMT</pubDate>
      <dc:creator>Oscar Flávio Jr</dc:creator>
      <category>AI Engineering</category>
      <description>What RAG is, how each stage works (chunking, embeddings, retrieval and generation), and how to build a local, private version with Ollama and Python.</description>
      <content:encoded><![CDATA[<h2 id="the-problem-rag-solves">The problem RAG solves</h2>
<p>A language model only knows what was in its training data. It doesn't know your company's internal documentation, your product manual or what changed last week. Asked about any of that, it tends to answer confidently and get it wrong.</p>
<p>RAG, described by Lewis and colleagues in 2020, separates two jobs: <strong>retrieving</strong> information from a trusted source and <strong>generating</strong> the answer in natural language. The model stops being the source of knowledge and becomes the writer of an answer based on the context it is given. Updating knowledge becomes a matter of re-indexing documents, not retraining a model.</p>

<h2 id="the-stages-of-a-rag-pipeline">The stages of a RAG pipeline</h2>
<figure class="figure">
  <div class="figure__frame" tabindex="0">
  <svg viewBox="0 0 680 230" role="img" aria-labelledby="rag-t rag-d" xmlns="http://www.w3.org/2000/svg">
  <title id="rag-t">RAG pipeline</title><desc id="rag-d">Indexing: documents are split into chunks, embedded and stored in a vector store. Query: the question is embedded, the closest chunks are retrieved and sent with the question to the language model, which writes the answer.</desc>
  <defs><marker id="ah-en-rag" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="dg-head" d="M0 0L10 5L0 10z"/></marker></defs>
  <text class="dg-label" x="0" y="14">INDEXING · ONCE PER DOCUMENT SET</text>
  <rect class="dg-box" x="0" y="26" width="140" height="44" rx="8"/><text class="dg-text" x="70" y="53" text-anchor="middle">Documents</text>
  <rect class="dg-box" x="180" y="26" width="140" height="44" rx="8"/><text class="dg-text" x="250" y="53" text-anchor="middle">Chunks</text>
  <rect class="dg-box" x="360" y="26" width="140" height="44" rx="8"/><text class="dg-text" x="430" y="53" text-anchor="middle">Embeddings</text>
  <rect class="dg-box dg-box--accent" x="540" y="26" width="140" height="44" rx="8"/><text class="dg-text" x="610" y="53" text-anchor="middle">Vector store</text>
  <path class="dg-line" pathLength="1" d="M140 48H174" marker-end="url(#ah-en-rag)"/>
  <path class="dg-line" pathLength="1" d="M320 48H354" marker-end="url(#ah-en-rag)"/>
  <path class="dg-line" pathLength="1" d="M500 48H534" marker-end="url(#ah-en-rag)"/>
  <text class="dg-label" x="0" y="150">QUERY · EVERY QUESTION</text>
  <rect class="dg-box" x="0" y="162" width="140" height="44" rx="8"/><text class="dg-text" x="70" y="189" text-anchor="middle">Question</text>
  <rect class="dg-box" x="180" y="162" width="140" height="44" rx="8"/><text class="dg-text" x="250" y="189" text-anchor="middle">Top-k retrieval</text>
  <rect class="dg-box dg-box--accent" x="360" y="162" width="140" height="44" rx="8"/><text class="dg-text" x="430" y="189" text-anchor="middle">LLM + context</text>
  <rect class="dg-box" x="540" y="162" width="140" height="44" rx="8"/><text class="dg-text" x="610" y="189" text-anchor="middle">Answer</text>
  <path class="dg-line" pathLength="1" d="M140 184H174" marker-end="url(#ah-en-rag)"/>
  <path class="dg-line" pathLength="1" d="M320 184H354" marker-end="url(#ah-en-rag)"/>
  <path class="dg-line" pathLength="1" d="M500 184H534" marker-end="url(#ah-en-rag)"/>
  <path class="dg-line" pathLength="1" d="M610 70V112H250V156" marker-end="url(#ah-en-rag)"/>
</svg>
  </div>
  <figcaption>The two halves of a RAG system. Indexing runs when documents change; retrieval and generation run for every question.</figcaption>
</figure>
<ol>
  <li><strong>Ingestion:</strong> extract text from the sources (Markdown, PDFs, web pages, tickets).</li>
  <li><strong>Chunking:</strong> split documents into pieces of a few hundred words.</li>
  <li><strong>Embeddings:</strong> turn each chunk into a numeric vector that represents its meaning.</li>
  <li><strong>Storage:</strong> keep chunks and vectors (in memory, in a file or in a vector database).</li>
  <li><strong>Retrieval:</strong> turn the question into a vector and find the closest chunks.</li>
  <li><strong>Generation:</strong> send the question and chunks to the model, with instructions to answer only from them.</li>
</ol>

<h2 id="running-ollama-locally">Running Ollama locally</h2>
<p>Ollama serves language and embedding models through a local HTTP API, on port 11434 by default. With Docker:</p>
<pre><code class="language-bash">docker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollama

docker exec ollama ollama pull nomic-embed-text
docker exec ollama ollama pull llama3.2</code></pre>
<p>These are two models with different roles: <code>nomic-embed-text</code> produces the vectors and <code>llama3.2</code> writes the answers. Any equivalent pair works, as long as the <strong>same embedding model</strong> is used to index the documents and to embed the questions. Changing the embedding model means re-indexing everything, because vectors from different models aren't comparable.</p>

<h2 id="a-minimal-rag-in-python">A minimal RAG in Python</h2>
<p>The example below uses only the <code>requests</code> library and cosine similarity computed in plain Python. It's meant for understanding the mechanism; for thousands of chunks, use a vector index.</p>
<pre><code class="language-python">import math
import requests

OLLAMA = &quot;http://localhost:11434&quot;

def embed(texts):
    response = requests.post(f&quot;{OLLAMA}/api/embed&quot;,
                             json={&quot;model&quot;: &quot;nomic-embed-text&quot;, &quot;input&quot;: texts})
    response.raise_for_status()
    return response.json()[&quot;embeddings&quot;]

def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

chunks = [
    &quot;The Pro plan allows up to 10 users and includes email support.&quot;,
    &quot;Refunds can be requested within 7 days of purchase.&quot;,
    &quot;The API is limited to 100 requests per minute per key.&quot;,
]
vectors = embed([&quot;search_document: &quot; + c for c in chunks])

def retrieve(question, k=2):
    q = embed([&quot;search_query: &quot; + question])[0]
    ranked = sorted(zip(chunks, vectors), key=lambda cv: cosine(q, cv[1]), reverse=True)
    return [chunk for chunk, _ in ranked[:k]]

def answer(question):
    context = &quot;\n&quot;.join(f&quot;[{i + 1}] {c}&quot; for i, c in enumerate(retrieve(question)))
    messages = [
        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: (
            &quot;Answer only from the provided context. &quot;
            &quot;If the answer is not in the context, say you don't know. &quot;
            &quot;Cite the passages you used as [n].&quot;)},
        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Context:\n{context}\n\nQuestion: {question}&quot;},
    ]
    response = requests.post(f&quot;{OLLAMA}/api/chat&quot;,
                             json={&quot;model&quot;: &quot;llama3.2&quot;, &quot;messages&quot;: messages, &quot;stream&quot;: False})
    response.raise_for_status()
    return response.json()[&quot;message&quot;][&quot;content&quot;]

print(answer(&quot;How long do I have to ask for a refund?&quot;))</code></pre>
<p>The <code>search_document:</code> and <code>search_query:</code> prefixes are a convention specific to <code>nomic-embed-text</code>, which was trained to tell documents and questions apart. Other embedding models have their own conventions or none at all; check the model's page.</p>

<h2 id="the-decisions-that-most-affect-quality">The decisions that most affect quality</h2>
<h3 id="chunk-size-and-boundaries">Chunk size and boundaries</h3>
<p>Chunks that are too large dilute meaning and eat into the model's context; chunks that are too small lose information needed to answer. A common starting point is 200 to 500 words with some overlap between neighbors. More important than the number is respecting the document's structure: splitting by section or heading avoids cutting an explanation in half.</p>
<h3 id="how-many-chunks-to-retrieve">How many chunks to retrieve</h3>
<p>Raising <code>k</code> increases the chance that the right chunk is in the context, but it also adds noise and slows generation on local models. Tune it with real questions, not intuition.</p>
<h3 id="where-to-store-the-vectors">Where to store the vectors</h3>
<p>For a few thousand chunks, an in-memory list is enough. Beyond that, a vector index avoids comparing the question with every vector. If the application already uses PostgreSQL, the pgvector extension stores embeddings next to the data and offers approximate indexes (HNSW and IVFFlat); the same practices for <a href="https://oscarflaviojr.com/writing/postgresql-indexes-explain-analyze.html">choosing and validating indexes with EXPLAIN ANALYZE</a> apply.</p>

<h2 id="evaluate-retrieval-separately-from-generation">Evaluate retrieval separately from generation</h2>
<p>When a RAG system answers wrongly, the cause is usually in one of two stages: the right chunk wasn't retrieved, or it was retrieved and the model didn't use it well. Mixing the two leads to tweaking the prompt when the problem was chunking.</p>
<p>A simple and effective practice is to build a list of real questions together with the chunk that should answer each one, and measure, before any generation, how often that chunk appears in the top <code>k</code>. Only once retrieval is good is it worth tuning the prompt and the generation model.</p>

<h2 id="limitations">Limitations</h2>
<ul>
  <li>RAG reduces made-up answers, but doesn't eliminate them; the model can still misread the context.</li>
  <li>Questions that require aggregating information across many documents ("how many customers complained about this?") aren't well served by similarity search.</li>
  <li>Small local models are faster and private, but follow instructions less strictly than larger ones.</li>
</ul>
<p>In production, a RAG assistant is a service like any other: it needs <a href="https://oscarflaviojr.com/writing/uptime-monitoring-consecutive-failures.html">uptime monitoring and alerting</a>, especially when it depends on a separate model server.</p>]]></content:encoded>
    </item>
    <item>
      <title>PostgreSQL indexes: B-tree, GIN and partial indexes, validated with EXPLAIN ANALYZE</title>
      <link>https://oscarflaviojr.com/writing/postgresql-indexes-explain-analyze.html</link>
      <guid isPermaLink="true">https://oscarflaviojr.com/writing/postgresql-indexes-explain-analyze.html</guid>
      <pubDate>Mon, 30 Nov 2026 12:00:00 GMT</pubDate>
      <dc:creator>Oscar Flávio Jr</dc:creator>
      <category>Software Engineering</category>
      <description>How to choose between B-tree, GIN, composite and partial indexes in PostgreSQL, read the plan with EXPLAIN ANALYZE, and create indexes without locking production.</description>
      <content:encoded><![CDATA[<h2 id="start-with-the-execution-plan">Start with the execution plan</h2>
<p>An index created without measuring is a guess. PostgreSQL shows exactly how it intends to run a query with <code>EXPLAIN</code>, and with <code>EXPLAIN ANALYZE</code> it actually runs the query and reports timings and real row counts for each step.</p>
<pre><code class="language-sql">EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;</code></pre>
<p>What to read in the output:</p>
<ul>
  <li><strong>Scan type:</strong> <code>Seq Scan</code> reads the whole table; <code>Index Scan</code> and <code>Bitmap Heap Scan</code> use an index; <code>Index Only Scan</code> answers from the index alone, without touching the table.</li>
  <li><strong>Estimated versus actual rows:</strong> <code>rows=</code> in the cost is the estimate; <code>actual ... rows=</code> is reality. Differences of orders of magnitude point to stale statistics; run <code>ANALYZE orders</code>.</li>
  <li><strong>Rows Removed by Filter:</strong> many rows read and discarded is a sign that the filter lacks a suitable index.</li>
  <li><strong>Buffers:</strong> <code>shared hit</code> came from memory, <code>read</code> came from disk. This helps separate a slow query from a cold cache.</li>
</ul>
<p>Careful: <code>EXPLAIN ANALYZE</code> executes the statement. To analyze an <code>UPDATE</code> or <code>DELETE</code>, wrap it in a transaction and undo it with <code>ROLLBACK</code>.</p>

<h2 id="b-tree-the-default-for-almost-everything">B-tree: the default for almost everything</h2>
<p>Without a type, <code>CREATE INDEX</code> creates a B-tree. It handles equality (<code>=</code>), ranges (<code>&lt;</code>, <code>&gt;</code>, <code>BETWEEN</code>), <code>IN</code>, <code>IS NULL</code>, and also avoids sorts, because it keeps values in order.</p>
<p>In composite indexes, column order matters. A B-tree is most efficient when the query constrains the leftmost columns. A rule that works well: columns compared by equality first, then the range or sort column.</p>
<pre><code class="language-sql">-- Serves WHERE customer_id = ? ORDER BY created_at DESC
CREATE INDEX index_orders_on_customer_id_and_created_at
  ON orders (customer_id, created_at DESC);</code></pre>
<p>This index also serves queries that filter only by <code>customer_id</code>, but it doesn't help much for queries that filter only by <code>created_at</code>.</p>

<h2 id="partial-indexes-for-frequent-subsets">Partial indexes for frequent subsets</h2>
<p>When queries almost always look at a small fraction of a table, such as pending orders in a table dominated by completed ones, a partial index covers only those rows. It is smaller, fits better in memory and costs less to maintain.</p>
<pre><code class="language-sql">CREATE INDEX index_orders_pending_on_created_at
  ON orders (created_at)
  WHERE status = 'pending';

-- Uses the index: the query's filter implies the index predicate
SELECT * FROM orders WHERE status = 'pending' AND created_at &lt; now() - interval '1 hour';</code></pre>
<p>The planner only uses a partial index when it can prove that the query's condition implies the index's condition. A generic parameter such as <code>status = $1</code> in a prepared plan can prevent that.</p>

<h2 id="gin-for-jsonb-arrays-and-text-search">GIN for jsonb, arrays and text search</h2>
<p>A B-tree compares whole values. To ask whether a <code>jsonb</code> document contains a key, whether an array contains an element or whether a text contains words, the right type is GIN, which indexes each inner element separately.</p>
<pre><code class="language-sql">-- jsonb_path_ops: smaller index, supports the containment operator @&gt;
CREATE INDEX index_events_on_payload
  ON events USING GIN (payload jsonb_path_ops);

SELECT * FROM events WHERE payload @&gt; '{&quot;type&quot;: &quot;signup&quot;}';</code></pre>
<p>The default <code>jsonb_ops</code> class also supports the key-existence operators (<code>?</code>, <code>?|</code>, <code>?&amp;</code>); <code>jsonb_path_ops</code> doesn't, but it is usually smaller and faster for containment. Choose based on the queries you actually run.</p>

<h2 id="creating-indexes-in-production-without-locking-the-table">Creating indexes in production without locking the table</h2>
<p>A plain <code>CREATE INDEX</code> blocks writes to the table until it finishes. On large tables that means minutes of stalled inserts and updates. <code>CREATE INDEX CONCURRENTLY</code> avoids the lock, at the cost of taking longer and not being allowed inside a transaction. In Rails:</p>
<pre><code class="language-ruby">class AddIndexToOrdersOnCustomerAndCreatedAt &lt; ActiveRecord::Migration[7.1]
  disable_ddl_transaction!

  def change
    add_index :orders, [:customer_id, :created_at],
              order: { created_at: :desc },
              algorithm: :concurrently
  end
end</code></pre>
<p>If a concurrent build fails halfway, PostgreSQL leaves an index marked as invalid. It isn't used by queries, but it is still updated on every write. Drop it with <code>DROP INDEX CONCURRENTLY</code> and try again.</p>

<h2 id="indexes-have-a-cost">Indexes have a cost</h2>
<p>Every index makes <code>INSERT</code> and <code>UPDATE</code> slower and takes disk and memory. It's worth periodically reviewing indexes that are never used:</p>
<pre><code class="language-sql">SELECT relname AS table_name, indexrelname AS index_name, idx_scan,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;</code></pre>
<p>Before dropping one, confirm that the statistics cover a representative period and that the index doesn't back a <code>UNIQUE</code> constraint.</p>
<p>Indexes fix slow queries, but they don't fix too many queries. If the log shows the same query repeated dozens of times per request, the problem is different: see <a href="https://oscarflaviojr.com/writing/rails-n-plus-one-queries.html">how to eliminate N+1 queries in Rails</a>. And if you store embeddings in PostgreSQL with pgvector, the same measure-before-you-index principle applies to the vector search described in <a href="https://oscarflaviojr.com/writing/local-rag-with-ollama.html">local RAG with Ollama</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>N+1 queries in Rails: how to find them, fix them and keep them from coming back</title>
      <link>https://oscarflaviojr.com/writing/rails-n-plus-one-queries.html</link>
      <guid isPermaLink="true">https://oscarflaviojr.com/writing/rails-n-plus-one-queries.html</guid>
      <pubDate>Mon, 30 Nov 2026 12:00:00 GMT</pubDate>
      <dc:creator>Oscar Flávio Jr</dc:creator>
      <category>Software Engineering</category>
      <description>What the N+1 problem is in Active Record, when to use includes, preload or eager_load, and how strict_loading stops regressions.</description>
      <content:encoded><![CDATA[<h2 id="what-an-n-1-query-is">What an N+1 query is</h2>
<p>The name describes the query count: <strong>1</strong> query to fetch the main list and <strong>N</strong> additional queries, one per item, when an association is accessed. The code looks harmless because Active Record loads associations lazily: the query only runs when the attribute is read.</p>
<pre><code class="language-ruby">posts = Post.order(created_at: :desc).limit(20)

posts.each do |post|
  puts &quot;#{post.title} — #{post.author.name}&quot;
end</code></pre>
<p>This snippet runs 21 queries: one for the posts and twenty for the authors. The development log makes the pattern easy to spot, because the same query repeats with different IDs:</p>
<pre><code class="language-sql">SELECT &quot;posts&quot;.* FROM &quot;posts&quot; ORDER BY &quot;posts&quot;.&quot;created_at&quot; DESC LIMIT 20
SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = $1 LIMIT 1  [[&quot;id&quot;, 7]]
SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = $1 LIMIT 1  [[&quot;id&quot;, 3]]
SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = $1 LIMIT 1  [[&quot;id&quot;, 7]]
...</code></pre>
<p>With 20 records the cost goes unnoticed. With a paginated list of 100 items and two associations per item, that is 201 round trips to the database per request, and the network latency between application and database starts to dominate response time.</p>

<h2 id="includes-preload-and-eager-load-which-one-to-use">includes, preload and eager_load: which one to use</h2>
<p>All three solve the problem by loading the association before the loop, but they generate different SQL.</p>
<div class="table-wrap" tabindex="0">
<table>
  <thead>
    <tr><th scope="col">Method</th><th scope="col">Generated SQL</th><th scope="col">When to use it</th></tr>
  </thead>
  <tbody>
    <tr><td><code>preload</code></td><td>One separate query per association, with <code>WHERE id IN (...)</code></td><td>When you only need to display the associated data</td></tr>
    <tr><td><code>eager_load</code></td><td>A single query with <code>LEFT OUTER JOIN</code></td><td>When you need to filter or sort by columns of the association</td></tr>
    <tr><td><code>includes</code></td><td>Uses <code>preload</code> by default and switches to <code>eager_load</code> when the query references the associated table</td><td>A reasonable default when you don't want to decide manually</td></tr>
  </tbody>
</table>
</div>
<pre><code class="language-ruby"># 2 queries: posts + authors WHERE id IN (...)
Post.preload(:author).limit(20)

# 1 query with LEFT OUTER JOIN, allows filtering by the association
Post.eager_load(:author).where(authors: { active: true })

# includes decides on its own: here it becomes eager_load because of the where on authors
Post.includes(:author).where(authors: { active: true })

# nested associations
Post.includes(comments: :author).limit(20)</code></pre>
<p>A practical note: <code>eager_load</code> on <code>has_many</code> associations multiplies the returned rows (a post with 50 comments becomes 50 rows in the result). For large lists, <code>preload</code> usually transfers less data, even though it runs more than one query.</p>

<h2 id="counting-count-size-and-counter-cache">Counting: count, size and counter_cache</h2>
<p>A less obvious N+1 shows up in counts. <code>post.comments.count</code> always runs a <code>SELECT COUNT(*)</code>, even when the comments were already loaded with <code>includes</code>. <code>post.comments.size</code>, on the other hand, uses the loaded collection when it exists and only queries the database when it doesn't.</p>
<pre><code class="language-ruby">posts = Post.includes(:comments).limit(20)

posts.each { |post| post.comments.count } # 20 COUNT queries, ignores the preload
posts.each { |post| post.comments.size }  # 0 extra queries</code></pre>
<p>When the page only needs the number, loading every comment is waste. In that case a <code>counter_cache</code> keeps the count in a column on the post itself:</p>
<pre><code class="language-ruby">class Comment &lt; ApplicationRecord
  belongs_to :post, counter_cache: true # requires a posts.comments_count column
end</code></pre>

<h2 id="preventing-regressions-with-strict-loading">Preventing regressions with strict_loading</h2>
<p>Fixing an N+1 once doesn't stop another one from appearing in the next view change. Since Rails 6.1, <code>strict_loading</code> turns lazy loading into an error, so the problem surfaces in tests instead of in production.</p>
<pre><code class="language-ruby"># On a single query
posts = Post.strict_loading.limit(20)
posts.first.author # =&gt; ActiveRecord::StrictLoadingViolationError

# On a whole model
class Post &lt; ApplicationRecord
  self.strict_loading_by_default = true
end

# Application-wide (config/application.rb or per environment)
config.active_record.strict_loading_by_default = true</code></pre>
<p>In an existing codebase, turning strict mode on globally breaks a lot at once. Gradual adoption works better: set <code>config.active_record.action_on_strict_loading_violation = :log</code> in production to only record violations, keep raising in development and test, and fix each spot as it shows up.</p>

<h2 id="how-to-find-n-1-queries-in-an-existing-application">How to find N+1 queries in an existing application</h2>
<ul>
  <li><strong>Development log:</strong> look for the same query repeated with different IDs within a single request.</li>
  <li><strong>The Bullet gem:</strong> detects N+1 queries and also the opposite case, when an <code>includes</code> loads data that is never used.</li>
  <li><strong>Tests with strict_loading:</strong> running the suite with strict mode on reveals the lazy-loading spots that your tests cover.</li>
  <li><strong>APM in production:</strong> tracing tools show requests with dozens of identical database spans.</li>
</ul>
<p>Once the N+1 is gone, the next bottleneck is usually the query itself. If it filters or sorts by columns without an index, see <a href="https://oscarflaviojr.com/writing/postgresql-indexes-explain-analyze.html">how to choose PostgreSQL indexes and validate them with EXPLAIN ANALYZE</a>. And to notice when a performance regression reaches production, <a href="https://oscarflaviojr.com/writing/uptime-monitoring-consecutive-failures.html">monitoring with a response-time threshold</a> helps you catch the slowdown before your users do.</p>]]></content:encoded>
    </item>
    <item>
      <title>Uptime monitoring: why you should alert only after consecutive failures</title>
      <link>https://oscarflaviojr.com/writing/uptime-monitoring-consecutive-failures.html</link>
      <guid isPermaLink="true">https://oscarflaviojr.com/writing/uptime-monitoring-consecutive-failures.html</guid>
      <pubDate>Mon, 30 Nov 2026 12:00:00 GMT</pubDate>
      <dc:creator>Oscar Flávio Jr</dc:creator>
      <category>Software Engineering</category>
      <description>How to build an availability monitor that catches real outages without false alarms: consecutive failures, detection time, states and a C# example.</description>
      <content:encoded><![CDATA[<h2 id="the-false-alarm-problem">The false-alarm problem</h2>
<p>The simplest possible monitor makes a request every minute and sends an alert if it fails. In practice it alerts far too often: a dropped packet, a DNS timeout, a restart during a deploy or a momentary glitch on the monitoring server itself all produce isolated failures that resolve on their own.</p>
<p>The effect is well known in operations: when most alerts require no action, people start ignoring them, and the real alert gets lost. Google's SRE book sums up the criterion: every alert should be actionable and point to a real problem for users.</p>

<h2 id="consecutive-failures-the-simplest-threshold-that-works">Consecutive failures: the simplest threshold that works</h2>
<p>Instead of alerting on the first failure, the monitor counts failures in a row and only alerts when the counter reaches a threshold <code>N</code>. Any success resets the counter. Isolated failures never reach the threshold; a real outage reaches it within a few cycles.</p>
<p>The same idea appears in established tools: in Prometheus, the <code>for</code> clause of an alerting rule requires the condition to hold for a period before the alert fires.</p>

<h2 id="how-long-it-takes-to-detect-an-outage">How long it takes to detect an outage</h2>
<p>The cost of the threshold is delay. In the worst case the outage starts right after a successful check, and the time until the alert is approximately <strong>interval × N + timeout</strong>.</p>
<div class="table-wrap" tabindex="0">
<table>
  <thead>
    <tr><th scope="col">Interval</th><th scope="col">Failures (N)</th><th scope="col">Timeout</th><th scope="col">Worst-case detection</th></tr>
  </thead>
  <tbody>
    <tr><td>60 s</td><td>1</td><td>10 s</td><td>~1 min 10 s, with many false positives</td></tr>
    <tr><td>60 s</td><td>3</td><td>10 s</td><td>~3 min 10 s</td></tr>
    <tr><td>30 s</td><td>3</td><td>10 s</td><td>~1 min 40 s</td></tr>
    <tr><td>300 s</td><td>2</td><td>10 s</td><td>~10 min 10 s</td></tr>
  </tbody>
</table>
</div>
<p>A shorter interval compensates for a larger <code>N</code> without increasing detection time. For most sites, checking every 30–60 seconds with <code>N = 3</code> is a good balance.</p>

<h2 id="think-in-states-not-checks">Think in states, not checks</h2>
<p>Another source of noise is alerting on every failed check once the threshold has been reached. A site that is down for an hour shouldn't produce 60 messages. Modeling the monitor as a small state machine solves this:</p>
<figure class="figure">
  <div class="figure__frame" tabindex="0">
  <svg viewBox="0 0 680 220" role="img" aria-labelledby="st-t st-d" xmlns="http://www.w3.org/2000/svg">
  <title id="st-t">Monitor state machine</title><desc id="st-d">Up moves to Suspect on a failure. Suspect returns to Up on a success, or moves to Down after N consecutive failures, sending one alert. Down moves to Recovered on the first success, sending one recovery notice, and then back to Up.</desc>
  <defs><marker id="ah-en-st" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="dg-head" d="M0 0L10 5L0 10z"/></marker></defs>
  <rect class="dg-box" x="0" y="70" width="140" height="44" rx="22"/><text class="dg-text" x="70" y="97" text-anchor="middle">Up</text>
  <rect class="dg-box" x="180" y="70" width="140" height="44" rx="22"/><text class="dg-text" x="250" y="97" text-anchor="middle">Suspect</text>
  <rect class="dg-box dg-box--accent" x="360" y="70" width="140" height="44" rx="22"/><text class="dg-text" x="430" y="97" text-anchor="middle">Down</text>
  <rect class="dg-box" x="540" y="70" width="140" height="44" rx="22"/><text class="dg-text" x="610" y="97" text-anchor="middle">Recovered</text>
  <path class="dg-line" pathLength="1" d="M140 92H174" marker-end="url(#ah-en-st)"/><text class="dg-label" x="160" y="60" text-anchor="middle">failure</text>
  <path class="dg-line" pathLength="1" d="M320 92H354" marker-end="url(#ah-en-st)"/><text class="dg-label" x="340" y="60" text-anchor="middle">N in a row</text>
  <path class="dg-line" pathLength="1" d="M500 92H534" marker-end="url(#ah-en-st)"/><text class="dg-label" x="520" y="60" text-anchor="middle">success</text>
  <path class="dg-line" pathLength="1" d="M240 70V30H70V64" marker-end="url(#ah-en-st)"/>
  <text class="dg-label" x="155" y="22" text-anchor="middle">success · reset counter</text>
  <path class="dg-line" pathLength="1" d="M610 114V170H70V120" marker-end="url(#ah-en-st)"/>
  <text class="dg-label" x="340" y="190" text-anchor="middle">back to up</text>
  <text class="dg-label" x="430" y="136" text-anchor="middle">1 alert</text>
  <text class="dg-label" x="618" y="136">1 notice</text>
</svg>
  </div>
  <figcaption>Alerts fire on transitions, not on every failed check: one alert when entering Down, one notice when recovering.</figcaption>
</figure>
<ul>
  <li><strong>Up:</strong> checks passing, counter at zero.</li>
  <li><strong>Suspect:</strong> one or more failures, below the threshold. No alert.</li>
  <li><strong>Down:</strong> threshold reached. One alert on entering this state, and none while it lasts.</li>
  <li><strong>Recovered:</strong> the first successful check after "down". Sends a recovery notice with the outage duration and returns to "up".</li>
</ul>

<h2 id="a-c-example">A C# example</h2>
<p>A minimal implementation with <code>HttpClient</code>. An <code>HttpClient</code> timeout surfaces as a <code>TaskCanceledException</code>; the <code>when</code> filter distinguishes it from a cancellation requested by the application itself.</p>
<pre><code class="language-csharp">public sealed class SiteMonitor
{
    private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(10) };
    private readonly Uri _url;
    private readonly int _threshold;
    private readonly Func&lt;string, Task&gt; _notify;
    private int _consecutiveFailures;
    private DateTimeOffset? _downSince;

    public SiteMonitor(Uri url, int threshold, Func&lt;string, Task&gt; notify)
    {
        _url = url;
        _threshold = threshold;
        _notify = notify;
    }

    public async Task CheckAsync(CancellationToken ct)
    {
        bool healthy;
        try
        {
            using var response = await _http.GetAsync(_url, ct);
            healthy = response.IsSuccessStatusCode;
        }
        catch (HttpRequestException)
        {
            healthy = false;
        }
        catch (TaskCanceledException) when (!ct.IsCancellationRequested)
        {
            healthy = false; // timeout
        }

        if (healthy)
        {
            if (_downSince is { } since)
                await _notify($&quot;{_url} is responding again after {DateTimeOffset.UtcNow - since:hh\\:mm\\:ss} down.&quot;);
            _consecutiveFailures = 0;
            _downSince = null;
            return;
        }

        _consecutiveFailures++;
        if (_downSince is null &amp;&amp; _consecutiveFailures &gt;= _threshold)
        {
            _downSince = DateTimeOffset.UtcNow;
            await _notify($&quot;{_url} is down after {_consecutiveFailures} consecutive failures.&quot;);
        }
    }
}</code></pre>
<p>The <code>HttpClient</code> is reused across checks; creating one instance per request can exhaust available sockets in long-running monitors.</p>

<h2 id="what-counts-as-a-failure">What counts as a failure</h2>
<p>An HTTP 200 doesn't guarantee the site works. A few extra checks catch failures the status code hides:</p>
<ul>
  <li><strong>Expected content:</strong> look for text that only appears on the correct page, to catch error pages served with status 200.</li>
  <li><strong>Response time:</strong> treat a response above a limit as a failure. A site that takes 20 seconds to respond is, in practice, down. Sudden slowness in Rails applications often comes from <a href="https://oscarflaviojr.com/writing/rails-n-plus-one-queries.html">N+1 queries</a> or <a href="https://oscarflaviojr.com/writing/postgresql-indexes-explain-analyze.html">missing indexes</a>.</li>
  <li><strong>TLS certificate:</strong> alert days in advance when the certificate is close to expiring.</li>
</ul>

<h2 id="check-from-more-than-one-place">Check from more than one place</h2>
<p>If the monitoring server loses its connection, every site appears down at the same time. Two measures prevent this: run the monitor outside the infrastructure it watches, and check from two or more locations, alerting only when the majority agrees. An "all sites went down at once" alert almost always points to a problem with the monitor itself.</p>]]></content:encoded>
    </item>
  </channel>
</rss>
