<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ugochukwu Okoli on Medium]]></title>
        <description><![CDATA[Stories by Ugochukwu Okoli on Medium]]></description>
        <link>https://medium.com/@okoliryan50?source=rss-1e470bd66360------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LwQ5628mr1Qr0xXi6ASEyQ.jpeg</url>
            <title>Stories by Ugochukwu Okoli on Medium</title>
            <link>https://medium.com/@okoliryan50?source=rss-1e470bd66360------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:24:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@okoliryan50/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to load test an application: find what saturates first, then prove it]]></title>
            <link>https://medium.com/@okoliryan50/how-to-load-test-an-application-find-what-saturates-first-then-prove-it-2fe6fa5dd3d9?source=rss-1e470bd66360------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe6fa5dd3d9</guid>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Ugochukwu Okoli]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 09:01:03 GMT</pubDate>
            <atom:updated>2026-11-26T09:01:03.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Cover: Find what saturates first. Requests queue before the narrow section of a pipe, which has no spare capacity." src="https://cdn-images-1.medium.com/max/1024/1*3YSBaEhlw7BhPpJ11QjwXg@2x.png" /></figure><p>“It handles 500 users” sounds like a result. It leaves out what those users did, how long the test ran, what “handles” meant, and what would have broken at 600.</p><p>A load test should answer a better question: where does the system bend, and why? At some load, one resource saturates first, meaning it has no spare capacity and work waits for it. It might be a CPU core, a database connection pool, a lock, a file descriptor limit or a network link. Use the test to find a suspect, then check it with server-side evidence and a controlled rerun.</p><p>Think of it as finding the narrowest pipe in a building. Water backing up in the kitchen tells you there is a problem. It doesn’t tell you which pipe.</p><p>This guide assumes you have never load tested. The method works for any application you are allowed to test. I use <a href="https://grafana.com/docs/k6/latest/">k6</a> for the code, but the steps don’t depend on it.</p><h3>Key terms</h3><p>Skim this now and come back when a term shows up.</p><h4>Percentiles: p50, p90, p95, p99</h4><p>A percentile tells you how long the faster share of requests took. Sort every response time from fastest to slowest. The p95 is the point that 95% of them are at or under.</p><ul><li><strong>p50 (median):</strong> Half of requests finished within this time. <em>Good for: the typical request.</em></li><li><strong>p90:</strong> 90% finished within this time; about 10% took longer. <em>Good for: an early view of the slower requests.</em></li><li><strong>p95:</strong> 95% finished within this time; about 5% took longer. <em>Good for: a common choice for targets.</em></li><li><strong>p99:</strong> 99% finished within this time; about 1% took longer. <em>Good for: the slow tail.</em></li><li><strong>Max:</strong> The single slowest request. <em>Good for: spotting extremes; one odd request can set it.</em></li><li><strong>Average:</strong> Total time divided by the number of requests. <em>Good for: a rough summary that can hide a slow group.</em></li></ul><p>For example, “p95 = 800 ms” means 95 of every 100 requests took 800 ms or less. It says nothing about how slow the other 5 were. They could have taken 810 ms or 30 seconds.</p><p>Three cautions:</p><ul><li>A small share can be many people. At 100,000 requests, the 1% beyond p99 is about 1,000 requests. One page view may make several requests, so a user has several chances to hit a slow one.</li><li>High percentiles need plenty of samples. With only 100 requests, one or two slow ones can move p99 a lot.</li><li>Don’t average percentiles. The average of ten p95 values is not the p95 of all those requests. Calculate it again from the underlying samples or from a histogram (counts of requests in time ranges) that can be merged.</li></ul><h4>Load and results</h4><ul><li><strong>Virtual user (VU):</strong> A simulated user run by the load testing tool.</li><li><strong>Concurrent users:</strong> Users active during the same period; they aren’t necessarily sending requests at the same instant.</li><li><strong>Throughput:</strong> Work completed per unit of time, such as requests per second (RPS).</li><li><strong>Latency, or response time:</strong> How long a request takes. Tools differ in what they include, so check.</li><li><strong>Error rate:</strong> The share of requests or actions that fail.</li><li><strong>Ramp and hold:</strong> Raising the load, then keeping it level.</li><li><strong>Surge and steady state:</strong> The rush as load arrives, and the behaviour after things settle.</li><li><strong>Baseline:</strong> A reference run that later runs are compared with.</li><li><strong>Threshold:</strong> A pass or fail limit set on a measurement.</li></ul><h4>Inside the system</h4><ul><li><strong>Saturation:</strong> A resource has no spare capacity, so work waits for it.</li><li><strong>Bottleneck:</strong> The resource that is currently limiting the system.</li><li><strong>Queue:</strong> Work waiting its turn.</li><li><strong>Connection pool:</strong> A limited set of reusable connections that requests share.</li><li><strong>Lock contention:</strong> Work waiting because something else holds a lock it needs.</li><li><strong>Event loop delay:</strong> In runtimes such as Node.js, how late scheduled work runs because the loop is busy.</li><li><strong>File descriptor:</strong> A handle the operating system uses for an open file or network connection.</li><li><strong>Memory leak:</strong> Memory that is kept after it is no longer needed, so use builds up.</li></ul><h3>1. Start with a question</h3><p>Before choosing a tool, write down what you want to learn and what “bad” means. For example:</p><blockquote><em>At what load does checkout stop meeting its target, and which resource is responsible?</em></blockquote><p>Then define the target with numbers you choose for your product:</p><ul><li><strong>Latency:</strong> for example, p95 is at most 500 ms for checkout requests. (Percentiles are explained under Key terms.)</li><li><strong>Errors:</strong> for example, fewer than 1% of requests fail.</li><li><strong>Correctness:</strong> for example, no duplicate orders, and every live update arrives.</li></ul><p>Those figures are placeholders. Take yours from what users will tolerate and what the business needs. Use percentiles, because an average can look fine while a slice of users waits many seconds. Always read latency next to the failure rate: requests that fail quickly can make latency look better.</p><p>A latency curve with a bend looks like this. The numbers are made up to show the shape.</p><figure><img alt="Sample chart: p95 response time stays nearly flat as users increase, bends around 350 users, then climbs steeply past an example 500 ms target." src="https://cdn-images-1.medium.com/max/1024/1*t4NUuSA3R8L3VMzHGwcd3A.png" /></figure><p><em>Sample data for illustration, not from a real test.</em></p><p>On the flat part, more load costs little. As a resource gets close to its limit, work starts waiting for it. If work keeps arriving faster than it can finish, the queue keeps growing. You are looking for the bend and for the queue behind it.</p><h3>2. Pick the test type</h3><p>Different questions need different traffic shapes. These names follow <a href="https://grafana.com/docs/k6/latest/testing-guides/test-types/">Grafana’s guide to load test types</a>, though what counts as “average” or “stress” depends on your system.</p><ul><li><strong>Smoke:</strong> A few users, briefly. <em>Do the script and the system work at all?</em></li><li><strong>Average load:</strong> Ramp to normal traffic and hold. <em>Does it meet its targets on a normal day?</em></li><li><strong>Stress:</strong> Ramp above normal and hold. <em>What degrades under heavy traffic?</em></li><li><strong>Spike:</strong> Jump up sharply, then drop. <em>Does it survive a sudden rush and recover?</em></li><li><strong>Soak:</strong> Normal load for hours. <em>Does something build up over time, such as a memory leak?</em></li><li><strong>Breakpoint:</strong> Keep increasing. <em>Where does it stop coping?</em></li></ul><p>Run a smoke test first, every time. A broken script can still produce graphs.</p><p>For a first investigation, I like a ladder: ramp to a level, hold it, then climb to the next. Pick levels around the traffic you expect and some distance beyond it.</p><h3>3. Read the system and make predictions</h3><p>Follow your most important user actions through the code. For each one, write down:</p><ul><li>Which requests, queries and outside services it calls, and in what order.</li><li>Which resources it shares with other users: CPU, memory, connection pools, locks, queues.</li><li>What is held while it waits. Database connections usually come from a connection pool, a limited set that requests share. A transaction is a group of database operations that succeed or fail together. One that makes several database calls keeps its connection for all of them.</li><li>Which limits exist on purpose: rate limits, size caps, quotas, timeouts.</li></ul><p>Then write predictions before you run anything. Writing down what you expect lets you compare it with what happens.</p><pre>Date and code version:<br>I expect the bend at about:<br>The first resource to saturate will be:<br>The first action to slow down will be:<br>The evidence that would prove me wrong:<br>A change I expect to help:</pre><p>Commit it, or put it somewhere with a timestamp. Keep the wrong guesses. They show where your model of the system was off.</p><h3>4. Model real traffic</h3><p>A loop that hits one endpoint as fast as possible tests that loop. Your users do several things, at different rates, with pauses between them. Write the model down:</p><ul><li><strong>What do users do?:</strong> The actions, their order and their mix.</li><li><strong>How often?:</strong> Pauses, timers, polling and heartbeats (periodic “still here” messages).</li><li><strong>What stays open?:</strong> WebSockets (connections kept open for two-way messages), server-sent events, uploads.</li><li><strong>How do they arrive and leave?:</strong> Login, join, leave, reconnect.</li><li><strong>What data do they touch?:</strong> Many records or a few popular ones, empty or large accounts.</li><li><strong>What differs between users?:</strong> Roles, session length, timing.</li></ul><p>Add random variation. If every simulated user starts a timer at the same moment and stays for exactly the same time, they act in waves, and your results show queues that your script created.</p><p>Find the product’s own limits early. If a script breaks a product rule, you will spend the test measuring rejections. For example, if one account may hold only five open orders, use enough test accounts or close orders as the script runs.</p><h4>Fixed users or fixed arrival rate?</h4><p>An iteration is one run of the script’s main function. In a <strong>closed model</strong>, each virtual user (VU) finishes one iteration before starting the next. If the server slows down, new work starts less often, so the load drops as the server slows. This can hide how bad a slow period is, because fewer requests are sent during it. This is related to coordinated omission (k6’s <a href="https://grafana.com/docs/k6/latest/using-k6/scenarios/concepts/open-vs-closed/">explanation</a>). In an <strong>open model</strong>, new iterations start on a schedule whether earlier ones have finished or not.</p><p>Use a closed model when a fixed group of users waits for each response. Use an arrival-rate model when requests or visitors keep coming regardless, as on many public sites and APIs. Either way, report the load you achieved (requests per second, completed actions) next to the load you intended.</p><p>Here is a small closed-model ladder. <a href="https://grafana.com/docs/k6/latest/set-up/install-k6/">Install k6</a>, save this as ladder.js, and try it with k6 run ladder.js. The localhost default is only for a smoke test on your own machine (shorten the stages for that).</p><pre>import http from &#39;k6/http&#39;;<br>import { check, sleep } from &#39;k6&#39;;<br> <br>const BASE_URL = __ENV.BASE_URL || &#39;http://localhost:3000&#39;;<br> <br>export const options = {<br>  scenarios: {<br>    ladder: {<br>      executor: &#39;ramping-vus&#39;,<br>      startVUs: 0,<br>      stages: [<br>        { duration: &#39;30s&#39;, target: 50 },<br>        { duration: &#39;2m&#39;, target: 50 },<br>        { duration: &#39;30s&#39;, target: 100 },<br>        { duration: &#39;2m&#39;, target: 100 },<br>        { duration: &#39;30s&#39;, target: 0 },<br>      ],<br>    },<br>  },<br>  summaryTrendStats: [&#39;avg&#39;, &#39;med&#39;, &#39;p(95)&#39;, &#39;p(99)&#39;, &#39;max&#39;],<br>  thresholds: {<br>    http_req_duration: [&#39;p(95)&lt;500&#39;],<br>    http_req_failed: [&#39;rate&lt;0.01&#39;],<br>  },<br>};<br> <br>export default function () {<br>  const list = http.get(`${BASE_URL}/api/products`);<br>  check(list, { &#39;list loaded&#39;: (r) =&gt; r.status === 200 });<br>  sleep(1 + Math.random() * 4); // a person reading the page<br> <br>  if (Math.random() &lt; 0.2) {<br>    const id = 1 + Math.floor(Math.random() * 100); // use a realistic spread<br>    const item = http.get(`${BASE_URL}/api/products/${id}`);<br>    check(item, { &#39;item loaded&#39;: (r) =&gt; r.status === 200 });<br>    sleep(1 + Math.random() * 4);<br>  }<br>}</pre><p>Replace the routes, IDs, mix, pauses and limits with your own.</p><p>The end-of-test summary and these thresholds cover the whole run, with all ramps and levels together, so a pass can hide a bad step. To get figures per step, save timestamped samples (k6 run -e BASE_URL=https://test.example.com --out csv=run1.csv ladder.js) and calculate latency, failures and request rate for each hold. A crossed threshold makes k6 exit with an error, but the run continues unless you set abortOnFail: true on that threshold. A failed check is only counted; add a threshold on checks if it should fail the run.</p><p>For an open model, use the constant-arrival-rate or ramping-arrival-rate executor, and set the rate or stage targets, timeUnit and preAllocatedVUs. The rate counts iterations, not requests. Remove the pause at the end of the iteration, because the executor does the pacing and a sleeping VU is still busy. Check dropped_iterations: k6 didn&#39;t start that work, often because no VU was free. You may have allocated too few, or a slowing system kept them busy longer.</p><h3>5. Prepare a safe test</h3><p><strong>Only load test systems you own or have written permission to test.</strong> If a hosting provider, database service or third-party API is in the path, read its rules too. Then:</p><ul><li><strong>Isolate the target.</strong> Use a separate app instance, database and signing secrets. Use synthetic data. A copy of production data is still real user data.</li><li><strong>Restrict access.</strong> If you relax protections for the test, allow only your load generator to reach it.</li><li><strong>Contain side effects.</strong> Stub or sandbox email, payments and webhooks.</li><li><strong>Set stop conditions.</strong> Decide when you will abort: errors above a limit, a host swapping, other services on the same machine suffering, a bill climbing.</li><li><strong>Cap the load.</strong> This matters most on a shared machine.</li><li><strong>Plan the cleanup.</strong> Remove test users, data, tokens, containers and temporary database copies.</li></ul><p>Next, make sure you will measure the application and not your test setup. If every virtual user logs in at the start, you may be testing password hashing and the login rate limit. When login isn’t the subject, create test users and short-lived tokens ahead of time, and test login separately. If a rate limit would hide what you want to see, raise it in the test environment only and record that you did. Run once with real limits too, since users will meet them.</p><p>A typical setup looks like this:</p><pre>load generator             test environment<br>+-------------+   HTTP /   +-------+     +-----+     +----------+<br>| k6 + script | ---------&gt; | proxy | --&gt; | app | --&gt; | database |<br>+------+------+ WebSocket  +-------+     +--+--+     +----+-----+<br>       |                                    |             |<br>  client metrics               app logs + host metrics    database samples</pre><p>Keep the load generator off the machine under test, or the two compete for CPU. Rehearse the whole thing at small scale, including monitoring and report generation, so an empty metrics file shows up before the real run.</p><h3>6. Measure both sides</h3><p>To explain what a simulated user experienced, record the server at the same time. Timestamp both so you can line them up.</p><ul><li><strong>Load generator.</strong> Record: Latency percentiles, failures, achieved rate, its own CPU. This shows: User experience, and whether the generator is struggling.</li><li><strong>App.</strong> Record: Server response time by route, errors, runtime delay, memory, pool size and waiting count. This shows: Time spent and queued inside the app.</li><li><strong>Host.</strong> Record: CPU per process and per core, CPU throttling (pauses enforced by a CPU limit) or steal (time a virtual machine waits while its host serves others), memory, swap, disk latency, open file descriptors (handles for files and sockets), TCP states and retransmits (data sent again). This shows: Machine and operating system limits.</li><li><strong>Database.</strong> Record: Active, idle and idle-in-transaction connections (a transaction is open but no query is running), lock waits, slow queries. This shows: Whether it is working, waiting or blocked.</li><li><strong>Dependencies.</strong> Record: Latency, errors, throttling. This shows: Delays that come from outside.</li></ul><p>To start, collect the k6 samples, your app’s request logs and, on a Linux host, vmstat 1. For Postgres, run this every few seconds:</p><pre>SELECT state, wait_event_type, count(*)<br>FROM pg_stat_activity<br>WHERE datname = current_database()<br>  AND backend_type = &#39;client backend&#39;<br>  AND pid &lt;&gt; pg_backend_pid()  -- leave out this query<br>GROUP BY 1, 2;</pre><p>Synchronise clocks, note the time each run starts, and save the raw files. You may need them for questions that a summary can’t answer.</p><p>In a Node app, log event loop delay too. It shows how late scheduled work runs because the main thread is busy. Node’s monitorEventLoopDelay reports it in nanoseconds.</p><p>Monitoring code can have bugs, so check its readings while the system is idle. If a reading isn’t what idle should look like, find out why.</p><h3>7. Run controlled steps</h3><ol><li>Smoke test. Confirm that requests succeed and every metric has data. If your app pushes live updates, check that they arrive.</li><li>Baseline. Run the ladder with current settings.</li><li>Hold each level. Give it time to settle. Longer holds show slower problems.</li><li>Form one explanation from the evidence.</li><li>Change one thing, rerun the same ladder, and compare.</li><li>Repeat important runs. One run per setting says nothing about how much results vary on their own.</li></ol><p>Keep a run log as you go:</p><pre>Run:           2 (compare with 1)<br>Code version:  &lt;commit&gt;<br>Changed:       database pool size, 10 -&gt; 30<br>Unchanged:     script, load settings, machine, data setup<br>Started:       &lt;time with time zone&gt;<br>Raw files:     &lt;folder&gt;<br>Observed:      &lt;what happened&gt;</pre><p>“The same command” is not enough. Record environment variables and defaults too, because a forgotten setting can change the workload.</p><p>Separate the surge from the steady state. When a step brings in new users, they log in, load data and connect at once. A percentile over the whole step mixes that rush with the calm after it. Report both.</p><p>A short ramp is a fair test of a sudden rush. To estimate steady capacity, ramp more slowly and hold longer.</p><h3>8. Read your results</h3><p>Before acting on any result, run the checks in section 10. Start with the shape of the graph, but never read latency alone. Put these on the same time axis:</p><ol><li>Latency: p50, p95 and p99, by route.</li><li>Throughput: the load you intended and the load you achieved.</li><li>Errors: how many, which kind and when they began.</li><li>Resources: CPU, memory, queues, connections and database activity.</li></ol><h4>Reading the sample chart</h4><p>Go back to the chart in section 1 and read it from left to right. Think of a road: extra cars make little difference until it starts to fill, then delays build quickly.</p><ul><li><strong>25 to 200 users.</strong> Look for: p95 rises slowly, from 112 to 131 ms. Likely meaning: In this range, added load costs little. Next: Check that throughput rose too, with few errors. Record which resources are growing.</li><li><strong>250 to 400 users.</strong> Look for: p95 rises from 145 to 420 ms, and each step adds more than the one before. Likely meaning: The bend: some work may be starting to wait. Next: Find the queue or resource that changes here. Hold these levels longer and add steps between them.</li><li><strong>400 to 500 users.</strong> Look for: p95 goes from 420 to 1,750 ms and passes the 500 ms target between 400 and 450. Likely meaning: The system misses the example target, and delay is growing fast. Next: Match the evidence to a cause, apply one fix and rerun the same steps.</li></ul><p>The bend appears before the target is missed. At 350 users the example still passes, with p95 at 230 ms, but the warning is already there. To name a cause, you need throughput, errors and server data.</p><p>After a fix, compare both curves. A bend that moves to a higher load suggests you gained room. A lower line that bends at the same place means requests got faster but the limit may not have moved. A new shape can mean another resource is now the bottleneck.</p><h4>Other shapes you might get</h4><p>The chart below shows eight shapes. It uses made-up data, and real results are usually noisier and may combine several shapes. Treat a shape as a lead to confirm with server data. In panels A to D and H, imagine each point is the settled result of a separate load level. Panels E to G show time. Latency is p95 except in D. In E, each dashed line marks when new users start arriving.</p><figure><img alt="Eight sample latency charts: flat, bend, slow from the start, slow tail, spikes when users arrive, climbing at steady load, regular spikes at steady load, and latency falling after errors start." src="https://cdn-images-1.medium.com/max/1024/1*7d3C-KSGS5R5dva75nobTw.png" /></figure><p><em>Sample data for illustration, not from a real test.</em></p><h4>A. Flat</h4><ul><li><strong>Look for:</strong> throughput rising as expected, few errors, and resources with room to spare.</li><li><strong>What it can mean:</strong> the system coped with this workload, up to this load, for this long. If latency is flat but throughput is too, check whether the generator added the load you intended.</li><li><strong>What to do:</strong> compare with your targets. To find the limit, test higher. To find slow build-up, hold longer.</li></ul><h4>B. Bend</h4><ul><li><strong>Look for:</strong> the first queue to grow near the bend, and whether throughput stops rising with the load.</li><li><strong>Possible causes:</strong> a saturated CPU, connection pool, database, lock, disk, network link or outside service.</li><li><strong>Possible fixes:</strong> match the fix to the resource. Profile and optimise busy code. Shorten transactions or speed up slow queries. Add capacity where it is short. Then rerun and see whether the bend moved.</li></ul><h4>C. Slow from the start</h4><ul><li><strong>Look for:</strong> latency that is already high with one or a few users.</li><li><strong>Possible causes:</strong> a missing database index, many calls made one after another, a distant dependency, a large response or expensive work on each request.</li><li><strong>Possible fixes:</strong> trace a single request and time each part. Add the right index, remove repeated calls, run independent calls in parallel, reduce the data or cache results where stale data is acceptable. More servers alone won’t make a slow single request much faster.</li></ul><h4>D. Slow tail</h4><ul><li><strong>Look for:</strong> a p50 that stays low while p99 climbs. Split results by route, server instance and type of data.</li><li><strong>Possible causes:</strong> contention on a few popular records, some unusually large accounts, pauses for garbage collection (the runtime reclaiming unused memory), empty caches, one unhealthy instance or an outside service that is sometimes slow.</li><li><strong>Possible fixes:</strong> follow what the slow requests have in common. Shorten lock time, fix the expensive query or page large results, reduce short-lived memory allocations, or repair the bad instance. Set sensible timeouts on outside calls.</li></ul><h4>E. Spikes when users arrive</h4><ul><li><strong>Look for:</strong> latency that jumps as load ramps and then recovers. Report the surge and the settled period separately.</li><li><strong>Possible causes:</strong> many new connections or logins at once, empty caches, slow startup of new instances, or a script that makes users act in step.</li><li><strong>Possible fixes:</strong> add realistic variation to the script. In the application, reuse connections, warm important caches, keep enough instances ready or limit how fast work is admitted. If real traffic arrives suddenly, don’t hide the problem by slowing the ramp.</li></ul><h4>F. Climbing at steady load</h4><ul><li><strong>Look for:</strong> what else grows over time: queues, memory, open connections, data or disk use.</li><li><strong>Possible causes:</strong> work arriving slightly faster than it finishes, a memory or connection leak, queries slowing as data grows, or a resource quota running down.</li><li><strong>Possible fixes:</strong> raise processing capacity or reduce incoming work, release leaked memory or connections, index or clean up growing data, and put limits on queues. Confirm with a longer soak.</li></ul><h4>G. Regular spikes at steady load</h4><ul><li><strong>Look for:</strong> an event with the same timing in logs and monitoring.</li><li><strong>Possible causes:</strong> garbage collection, scheduled jobs, database maintenance or checkpoints, cache entries expiring together, autoscaling, or timers in your test script.</li><li><strong>Possible fixes:</strong> first match the timing. Then reduce allocations, move or split a heavy job, tune the maintenance involved, vary cache expiry times or remove synchronisation from the script.</li></ul><h4>H. Faster, but failing</h4><ul><li><strong>Look for:</strong> latency falling while errors rise. Compare successful and failed requests separately.</li><li><strong>Possible causes:</strong> rate limiting, a service rejecting excess work, a dependency failing, a circuit breaker opening (it stops calls to a failing service), or crashed instances behind a proxy.</li><li><strong>Possible fixes:</strong> use status codes and logs to find who rejects the request and why. Fix the failure. If the rejection is deliberate protection, decide whether the limit and the client’s retry behaviour suit your target. Don’t count fast failures as better performance.</li></ul><h4>Two more results to watch for</h4><ul><li><strong>Load rises but throughput stays level or falls.</strong> Check: Queues, timeouts, retries, achieved load and generator health. Likely direction: Find the limit; if retries add load, cap them and add increasing, randomised delays.</li><li><strong>Results change a lot between identical runs.</strong> Check: Background jobs, cache state, data size, shared hardware and warm-up. Likely direction: Control what you can, repeat, and report the range.</li></ul><p>After any fix, rerun the same workload. Check that the symptom and the suspected resource both improved, and that errors or another measure didn’t get worse.</p><h3>9. Connect symptoms to causes</h3><p>Once the graph’s shape tells you where to look, use this section to test a cause against server evidence. Ask: is the application busy, or is it waiting? High CPU and a delayed runtime point one way. Quiet CPU and a growing queue point another.</p><p>Treat each row as a lead to confirm. Several problems can happen together.</p><ul><li><strong>One core near 100%, event loop or run queue (work waiting for CPU) delayed.</strong> Suspect: CPU bound. Confirm with: A CPU profile under load. Possible next change: Optimise the code the profile points to, send less data, or add processes if cores are spare.</li><li><strong>Pool queue that persists, database connections mostly </strong><strong>active.</strong> Suspect: Slow work in the database: queries, CPU, disk or locks. Confirm with: Wait events, query timings, database CPU and disk. Possible next change: Fix what they show before enlarging the pool.</li><li><strong>Pool queue that persists, connections mostly idle or idle in transaction.</strong> Suspect: Connections held while the app does something else (network trips, outside calls, a busy runtime), or never released. Confirm with: Transaction traces, round-trip time, app CPU and runtime delay. Possible next change: Hold connections for less time and fix leaks, then try a bigger pool within the database’s limit.</li><li><strong>Queries waiting on locks, popular records slowest.</strong> Suspect: Lock contention. Confirm with: Which query blocks which. Possible next change: Shorter transactions, less contention.</li><li><strong>Slow while CPU has room, high I/O wait or disk latency.</strong> Suspect: Disk. Confirm with: Disk latency and utilisation. Possible next change: Read and write less, add a missing index, or use faster storage.</li><li><strong>Latency spikes in a container or small VM while average CPU looks moderate.</strong> Suspect: CPU throttling or steal. Confirm with: Container throttling counters, steal time. Possible next change: Raise the quota or change the instance type.</li><li><strong>New connections failing, descriptors near their limit, “too many open files”.</strong> Suspect: File descriptor limit. Confirm with: The running process’s limits and logs. Possible next change: Raise the limit, check for unclosed handles.</li><li><strong>New connections failing, descriptors fine.</strong> Suspect: Ports or connection queues exhausted. Confirm with: Use of ephemeral ports (temporary ports for outgoing connections) on the generator and proxy; overflows of the listen queue (incoming connections waiting to be accepted). Possible next change: Reuse connections, or tune the limit you found.</li><li><strong>Slow at the client, fast at the server.</strong> Suspect: The path, the load generator, or waiting before the server’s timer starts. Confirm with: Where that timer starts, proxy timings, runtime delay, a second generator. Possible next change: Fix whichever part is slow.</li><li><strong>Retransmits rising, other resources quiet.</strong> Suspect: Network. Confirm with: Interface and provider graphs. Possible next change: Reduce traffic or address the link.</li><li><strong>Memory climbing through a soak and not recovering after cleanup or garbage collection.</strong> Suspect: Memory leak. Confirm with: Heap or allocation snapshots over time. Possible next change: Release what is being retained.</li><li><strong>Swap in use, little memory available.</strong> Suspect: Memory pressure on the host. Confirm with: Per-process memory, swap activity. Possible next change: Use less memory or add more.</li><li><strong>Many 429 (“too many requests”) responses.</strong> Suspect: A rate limiter. Confirm with: Response headers, limiter settings. Possible next change: Decide whether the limit is intended, and test accordingly.</li><li><strong>Many 5xx (server error) responses.</strong> Suspect: An application or dependency failure. Confirm with: Logs and traces for the same timestamps. Possible next change: Fix the error, then rerun.</li></ul><p>Making a connection pool bigger lets more work reach the database at once. That helps when connections are the shortage. It can hurt when the database is already struggling, and every database has a connection limit.</p><h3>10. Distrust the first result</h3><p>A surprising result may be about your test. Check four things.</p><p>Start with the load generator. Is it short of CPU, memory or network? Did it produce the load you intended?</p><p>Then look at the path. Local proxies, container networking, VPNs and home connections all add to what the client measures. Compare client and server timings over the same time window and the same routes. If you can, run the same test along a shorter path and see what changes.</p><p>For the script, read the failures. Are they application bugs, or did the script break a product rule?</p><p>Finally, check the measurements. Look at what each number means. If you time live updates, could an old stored update be counted as a slow new delivery? Is a CPU figure for the last interval, or an average over the process’s whole life (as with ps %cpu)? Are you watching the server process or its shell wrapper? Did your script synchronise its users?</p><p>When client and server disagree, find out what each number includes before you rely on either.</p><h3>11. Fix, retest and report</h3><p>Once you have an explanation, test it. Predict what the change should do to both the user-facing number and the suspected resource. If latency improves but the resource behaves as before, your explanation may be wrong. Look for what got worse, too.</p><p>For example (hypothetical), if you suspect a slow query is filling the connection pool, predict that fixing it will cut query time, pool waiting and p95. Rerun the same load and check all three.</p><p>When you report your own results, include:</p><ul><li>The question, and your predictions.</li><li>The workload, environment, code version and settings.</li><li>Achieved load, latency percentiles and errors for each step.</li><li>The server-side evidence for your explanation.</li><li>What you changed, and what improved or got worse.</li><li>Missing data, variation between runs and what you couldn’t test.</li></ul><p>Aim for a conclusion another developer can check, such as: “At this workload, this queue grew, this change shrank it, and these questions remain.”</p><h3>12. Your load test checklist</h3><p>Copy this into your next test plan.</p><p><strong>Question and safety</strong></p><ul><li>☐ I own the system, or have written permission to test it</li><li>☐ I have written the question and the targets for latency, errors and correctness</li><li>☐ The app, data and secrets are isolated from production</li><li>☐ Side effects are stubbed, and access is restricted</li><li>☐ I have a load cap, stop conditions and a cleanup plan</li></ul><p><strong>Design</strong></p><ul><li>☐ I chose a test type that fits the question</li><li>☐ I traced the key actions through the code</li><li>☐ I wrote down predictions before running</li><li>☐ The traffic model covers actions, timing, connections, data and variation</li><li>☐ I chose a closed or arrival-rate model deliberately</li><li>☐ The script respects product limits</li></ul><p><strong>Measurement</strong></p><ul><li>☐ A smoke test passes and every metric has data</li><li>☐ I checked the monitoring against an idle system</li><li>☐ Client, app, host and database data share a timeline</li><li>☐ I am watching the load generator’s own health</li></ul><p><strong>Runs</strong></p><ul><li>☐ I have a baseline</li><li>☐ I record settings, code version and raw files for every run</li><li>☐ I change one thing per comparison</li><li>☐ I report achieved load, and separate surge from steady state</li><li>☐ I repeat the runs my conclusion depends on</li></ul><p><strong>Report</strong></p><ul><li>☐ I confirmed the suspected bottleneck with server-side evidence</li><li>☐ I checked what got worse after the fix</li><li>☐ I listed wrong predictions, missing data and untested cases</li><li>☐ I cleaned up test data, tokens and infrastructure</li></ul><p>Start small: one important user action, one smoke test and one prediction. When the graph bends, look for the queue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe6fa5dd3d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Deploy Every Side Project to a $3 VPS: One Image per Commit, Automatic Rollback]]></title>
            <link>https://medium.com/@okoliryan50/how-i-deploy-every-side-project-to-a-3-vps-one-image-per-commit-automatic-rollback-146ae9deaa11?source=rss-1e470bd66360------2</link>
            <guid isPermaLink="false">https://medium.com/p/146ae9deaa11</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ugochukwu Okoli]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 14:40:28 GMT</pubDate>
            <atom:updated>2026-11-16T14:50:27.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Cover: “One image per commit.” A row of commit images flows through a health check into a $3 VPS, with a dashed rollback line to the previous image." src="https://cdn-images-1.medium.com/max/1024/1*BwOPacSX2-Gr8tyOVtmgmg.jpeg" /></figure><p>This is what happens when I push to main, on every project I run:</p><figure><img alt="Flowchart of the deploy pipeline: git push to main, test job, build an image tagged with the commit SHA, push to GHCR, deploy job SSHes to the VPS, docker compose pull and up, wait for a healthy status or roll back to the previous image, then the runner checks the public URL. Failures stop the job at each step." src="https://cdn-images-1.medium.com/max/1024/1*xm7vEBKwAv4V06L2cX43LA.png" /></figure><p>GitHub Actions tests the code, builds one Docker image for that commit, and pushes it to GitHub Container Registry (GHCR). It then SSHes into a $3-a-month InterServer VPS, which pulls that exact image and starts it. If the new container doesn’t report healthy in time, the server puts the previous image back and the job fails. Last, the job requests the public URL from outside the server.</p><p>The stack doesn’t matter. Anything that builds into a container image goes through the same three jobs and the same deploy script. Per project, I change the test command, the path filters and a few names; the script itself stays untouched.</p><p>It’s around 150 lines of YAML and one Bash script. It gives me deploy on push, immutable releases, automatic rollback and one-command manual rollback, without Kubernetes, Terraform, or a platform bill that grows with every service.</p><h3>The box</h3><p>The VPS is InterServer’s smallest Linux plan: one “slice” at $3/month, with 1 core, 2 GB RAM, 40 GB SSD and 2 TB of transfer. Pricing is linear at $3 per slice, and you can add slices to an existing VPS when it needs more CPU, memory or disk. Four slices are $12 for 2 cores and 8 GB. That’s the whole scaling plan: start on one slice, and add slices when the numbers say so.</p><p>A typical project on it has three parts:</p><ul><li><strong>The API</strong>, in a container.</li><li><strong>Postgres</strong>, in a container next to it on a named volume, with no published host port. It’s reachable only on the compose network.</li><li><strong>Static frontends</strong> (a landing page, a dashboard), built into one nginx image.</li></ul><p>These are two deploy units with two workflows. The API and database form one Docker Compose project in ~/myapp; the frontends form a second in ~/myapp-web. A frontend deploy never restarts the API.</p><p>Caddy runs on the host and terminates HTTPS. Each site is three lines:</p><pre>api.example.com {<br>    reverse_proxy 127.0.0.1:8081<br>}</pre><p>Caddy fetches and renews its own certificates and passes WebSockets through without extra configuration.</p><p>Here’s the API service from the compose file. Everything else in this article hangs off it:</p><pre>name: myapp<br>services:<br>  api:<br>    image: ${APP_IMAGE:?set APP_IMAGE, for example ghcr.io/owner/myapp:&lt;commit-sha&gt;}<br>    container_name: myapp-api<br>    restart: unless-stopped<br>    ports:<br>      - &quot;127.0.0.1:${APP_PORT:-8081}:8080&quot;<br>    env_file: .env<br>    read_only: true<br>    tmpfs:<br>      - /tmp<br>    cap_drop:<br>      - ALL<br>    security_opt:<br>      - no-new-privileges:true<br>    mem_limit: 512m<br>    pids_limit: 200<br>    logging:<br>      driver: json-file<br>      options: { max-size: &quot;10m&quot;, max-file: &quot;3&quot; }</pre><p>Four things to note:</p><ol><li><strong>image comes from a variable.</strong> The deploy script sets APP_IMAGE to a commit-specific tag, so the compose file never names a version. After each deploy the script also writes the running tag into the project&#39;s .env, which Compose reads for interpolation. That way docker compose ps and logs work when you SSH in, and an exported APP_IMAGE still overrides it.</li><li><strong>The port is published on </strong><strong>127.0.0.1 only.</strong> Docker-published ports bypass UFW and most iptables firewall rules, so binding to loopback is the actual protection, not a nicety. The only way in from the internet is through Caddy.</li><li><strong>The hardening keys apply to the API service only.</strong> A read-only root filesystem, dropped capabilities and no-new-privileges limit what a compromised process can change or escalate to. The official Postgres image needs capabilities to start, so it doesn&#39;t get the same treatment. Run the API as a non-root user too (USER node in a Node image).</li><li><strong>Limits have to fit in RAM.</strong> On a 2 GB box, a 512 MB API, a Postgres capped around the same, Caddy and the OS leave headroom. A limit contains a leak only if the sum of the limits fits in physical memory; otherwise the kernel’s OOM killer picks a victim, and it may be your database.</li></ol><p>The logging block rotates logs, which keeps docker logs from slowly filling a 40 GB disk.</p><h3>The pipeline</h3><p>The API workflow has three jobs, test, build and deploy, each depending on the one before it.</p><h4>Trigger only on what changed, one deploy at a time</h4><pre>on:<br>  push:<br>    branches: [main]<br>    paths:<br>      - &#39;server/**&#39;<br>      - &#39;deploy/**&#39;<br>      - &#39;.github/workflows/deploy.yml&#39;<br>  workflow_dispatch:<br>concurrency:<br>  group: deploy-production<br>  cancel-in-progress: false</pre><p>Editing the landing page doesn’t redeploy the API. Including deploy/** matters: the compose file and script are shipped on every deploy, so a change to them should trigger one. workflow_dispatch adds a &quot;Run workflow&quot; button for redeploying without a code change.</p><p>With concurrency, a second push waits for the running deploy instead of racing it. If several pushes queue up, GitHub keeps only the newest pending run, which is what you want. cancel-in-progress: false stops a new push from killing a deploy halfway through, which could leave the server between releases with nobody watching the health check. Give the frontend workflow its own group (deploy-production-web); if both share one, a frontend push can cancel a pending API deploy.</p><h4>Test against a real database</h4><pre>test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: 22<br>      - run: npm ci &amp;&amp; npm test</pre><p>GitHub’s Ubuntu runners have Docker, so integration tests can start a throwaway Postgres with Testcontainers instead of mocking it. Pin the same Postgres major version as the compose file. If tests fail, no image is built.</p><h4>Build one image per commit, tagged with the SHA</h4><pre>build:<br>    needs: test<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: read<br>      packages: write<br>    outputs:<br>      image: ${{ steps.ref.outputs.image }}<br>    steps:<br>      - uses: actions/checkout@v4<br>      # Image names must be lowercase, and the owner or repo name may not be.<br>      - id: ref<br>        run: echo &quot;image=ghcr.io/${GITHUB_REPOSITORY,,}&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;<br>      - uses: docker/setup-buildx-action@v3<br>      - uses: docker/login-action@v3<br>        with:<br>          registry: ghcr.io<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GITHUB_TOKEN }}<br>      - uses: docker/build-push-action@v6<br>        with:<br>          context: server<br>          push: true<br>          tags: |<br>            ${{ steps.ref.outputs.image }}:${{ github.sha }}<br>            ${{ steps.ref.outputs.image }}:latest<br>          labels: |<br>            org.opencontainers.image.source=https://github.com/${{ github.repository }}<br>          cache-from: type=gha<br>          cache-to: type=gha,mode=max</pre><ul><li><strong>${GITHUB_REPOSITORY,,}</strong> is Bash lowercasing. GHCR rejects capitals, and GitHub names often have them.</li><li><strong>The SHA tag is the release identifier.</strong> The deploy job passes &lt;image&gt;:&lt;sha&gt; to the server, never :latest. The server runs the commit that passed the tests, even if another push lands seconds later.</li><li><strong>CI needs no registry secret.</strong> The workflow’s own GITHUB_TOKEN pushes, given packages: write. The source label connects the package to the repository, so it appears there and inherits its access settings.</li><li><strong>setup-buildx-action is required</strong> for the type=gha layer cache. To make the cache pay off, copy dependency manifests and install before copying the source, so code-only changes reuse the install layer:</li></ul><pre>COPY package.json package-lock.json ./<br>RUN npm ci --no-audit --no-fund<br>COPY src ./src</pre><h4>Deploy over SSH with a pinned host key</h4><pre>deploy:<br>    needs: build<br>    runs-on: ubuntu-latest<br>    environment: production<br>    env:<br>      VPS_HOST: ${{ secrets.VPS_HOST }}<br>      VPS_USER: ${{ secrets.VPS_USER }}<br>      IMAGE_REF: ${{ needs.build.outputs.image }}:${{ github.sha }}<br>      APP_URL: ${{ vars.APP_URL }}<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Prepare SSH<br>        env:<br>          SSH_KEY: ${{ secrets.VPS_SSH_KEY }}<br>          KNOWN_HOSTS: ${{ secrets.VPS_KNOWN_HOSTS }}<br>        run: |<br>          install -m 700 -d ~/.ssh<br>          printf &#39;%s\n&#39; &quot;$SSH_KEY&quot; | tr -d &#39;\r&#39; &gt; ~/.ssh/id_ed25519<br>          chmod 600 ~/.ssh/id_ed25519<br>          printf &#39;%s\n&#39; &quot;$KNOWN_HOSTS&quot; &gt; ~/.ssh/known_hosts<br>      - name: Send the compose file and deploy script<br>        run: |<br>          ssh &quot;$VPS_USER@$VPS_HOST&quot; &#39;mkdir -p ~/myapp&#39;<br>          scp deploy/docker-compose.yml deploy/remote-deploy.sh &quot;$VPS_USER@$VPS_HOST:~/myapp/&quot;<br>      - name: Pull and restart on the VPS<br>        run: ssh &quot;$VPS_USER@$VPS_HOST&quot; &quot;bash ~/myapp/remote-deploy.sh &#39;$IMAGE_REF&#39; ~/myapp&quot;</pre><p>VPS_KNOWN_HOSTS holds ssh-keyscan output captured at setup. Check the fingerprint once against your provider&#39;s console, because a keyscan trusts whatever answers. The entry must match VPS_HOST exactly, IP or hostname. From then on the runner refuses to connect to anything else at that address. Tutorials that use StrictHostKeyChecking=no quietly drop that protection.</p><p>tr -d &#39;\r&#39; is there because pasting a private key into GitHub&#39;s secrets UI on Windows can add carriage returns, which OpenSSH rejects with an unhelpful error.</p><p>The compose file and script are versioned in the repository and copied on every deploy, so the server’s configuration follows Git. The one file never shipped is .env, with the database password and signing keys, which lives only on the server.</p><h4>Check the public URL from outside</h4><pre>- name: Check the public address<br>        run: |<br>          for attempt in $(seq 1 10); do<br>            if curl -fsS --max-time 8 &quot;$APP_URL/health/ready&quot; &gt;/dev/null; then<br>              echo &quot;up on attempt $attempt&quot;; exit 0<br>            fi<br>            echo &quot;attempt $attempt: not answering yet&quot;; sleep 3<br>          done<br>          echo &quot;::error::$APP_URL did not answer. Check Caddy and DNS.&quot;; exit 1</pre><p>A container can be healthy on loopback while users can’t reach it: a broken Caddy block, a DNS change, an expired certificate. This step catches those. It doesn’t roll back, because older code won’t fix a DNS fault. It turns the job red so I find out from CI rather than from a user.</p><h3>remote-deploy.sh: where rollback happens</h3><p>The script runs on the server. Its header maps the variables the workflows pass in:</p><pre>set -euo pipefail<br>IMAGE_REF=&quot;${1:?usage: remote-deploy.sh &lt;image:tag&gt; [app-dir]}&quot;<br>APP_DIR=&quot;${2:-$HOME/myapp}&quot;<br>SERVICE=&quot;${APP_SERVICE:-api}&quot;<br>CONTAINER=&quot;${APP_CONTAINER:-myapp-api}&quot;<br>WAIT_SECONDS=&quot;${APP_WAIT_SECONDS:-120}&quot;<br>say() { printf &#39;\n==&gt; %s\n&#39; &quot;$*&quot;; }<br>die() { printf &#39;\nERROR: %s\n&#39; &quot;$*&quot; &gt;&amp;2; exit 1; }<br>cd &quot;$APP_DIR&quot;<br>compose() { docker compose &quot;$@&quot;; }</pre><p>Then the deploy itself:</p><pre># What is running now, so a bad release can be undone. Empty on the very first deploy.<br>PREVIOUS=&quot;$(docker inspect --format &#39;{{.Config.Image}}&#39; &quot;$CONTAINER&quot; 2&gt;/dev/null || true)&quot;<br># Pull first: if this fails, the running containers are untouched.<br>export APP_IMAGE=&quot;$IMAGE_REF&quot;<br>compose pull &quot;$SERVICE&quot; || die &quot;could not pull $IMAGE_REF. Is this machine logged in to ghcr.io?&quot;<br>if ! compose up -d --remove-orphans; then<br>  STATUS=&quot;could not start&quot;<br>else<br>  STATUS=&quot;timed out&quot;<br>  for _ in $(seq 1 &quot;$WAIT_SECONDS&quot;); do<br>    HEALTH=&quot;$(docker inspect --format &#39;{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}&#39; &quot;$CONTAINER&quot; 2&gt;/dev/null || echo missing)&quot;<br>    # restart: unless-stopped keeps a crashing container &quot;running&quot;; RestartCount gives it away<br>    STATE=&quot;$(docker inspect --format &#39;{{.State.Running}} {{.RestartCount}}&#39; &quot;$CONTAINER&quot; 2&gt;/dev/null || echo &#39;false 0&#39;)&quot;<br>    if [ &quot;$HEALTH&quot; = &quot;healthy&quot; ]; then STATUS=&quot;healthy&quot;; break; fi<br>    if [ &quot;$HEALTH&quot; = &quot;unhealthy&quot; ]; then STATUS=&quot;unhealthy&quot;; break; fi<br>    if [ &quot;$STATE&quot; != &quot;true 0&quot; ]; then STATUS=&quot;container crashed&quot;; break; fi<br>    sleep 1<br>  done<br>fi<br>if [ &quot;$STATUS&quot; = &quot;healthy&quot; ]; then<br>  sed -i &#39;/^APP_IMAGE=/d&#39; .env &amp;&amp; echo &quot;APP_IMAGE=$IMAGE_REF&quot; &gt;&gt; .env<br>  # ...remove old local images, keeping this one and $PREVIOUS<br>  exit 0<br>fi</pre><p>In order, it:</p><ol><li><strong>Records what’s running</strong> by reading the image off the live container. That’s the rollback target, and nothing outside the server tracks release history.</li><li><strong>Pulls before it stops anything.</strong> If GHCR is down or the server’s login has expired, the old release keeps serving.</li><li><strong>Waits for Docker’s health status</strong>, not just a started process. It stops waiting early if the container goes unhealthy or crashes. Because of restart: unless-stopped, a container that dies on boot keeps getting restarted and looks &quot;running&quot;, so the loop watches RestartCount instead. That distinction is why I wrote the loop rather than using docker compose up --wait.</li><li><strong>Rolls back</strong> if the release isn’t healthy:</li></ol><pre>compose logs --tail 40 &quot;$SERVICE&quot; 2&gt;&amp;1 | sed &#39;s/^/    /&#39; &gt;&amp;2 || true<br>if [ -n &quot;$PREVIOUS&quot; ] &amp;&amp; [ &quot;$PREVIOUS&quot; != &quot;$IMAGE_REF&quot; ]; then<br>  say &quot;rolling back to $PREVIOUS&quot;<br>  APP_IMAGE=&quot;$PREVIOUS&quot; compose up -d --force-recreate --pull never &quot;$SERVICE&quot; || true<br>  sed -i &#39;/^APP_IMAGE=/d&#39; .env &amp;&amp; echo &quot;APP_IMAGE=$PREVIOUS&quot; &gt;&gt; .env<br>  die &quot;rolled back to $PREVIOUS. The new release failed: $STATUS&quot;<br>fi<br>die &quot;the deploy failed ($STATUS) and there is no previous release to go back to&quot;</pre><p>The failed container’s last 40 log lines land in the Actions log, so most failed deploys are diagnosable without SSHing in. --pull never forces the rollback to use the image already on disk.</p><p>The script doesn’t wait for the rolled-back container to report healthy. It was healthy before this deploy, but if the bad release ran a destructive migration, it might not be. On the very first deploy there’s nothing to roll back to, so the job fails and leaves the broken release in place.</p><p>On success, the script deletes old local images except the current and previous ones, so a rollback target is always on disk and 40 GB lasts.</p><p>Manual rollback is one command, run in ~/myapp:</p><pre>APP_IMAGE=ghcr.io/&lt;owner&gt;/&lt;repo&gt;:&lt;older-sha&gt; docker compose up -d api</pre><p>It reaches back as far as the registry keeps images. A weekly workflow (actions/delete-package-versions) keeps the newest 10.</p><p>The frontend workflow reuses the same script with different variables, on one line:</p><pre>run: ssh &quot;$VPS_USER@$VPS_HOST&quot; &quot;APP_SERVICE=web APP_CONTAINER=myapp-web APP_WAIT_SECONDS=60 bash ~/myapp-web/remote-deploy.sh &#39;$IMAGE_REF&#39; ~/myapp-web&quot;</pre><h4>Health checks that test something real</h4><p>The script trusts Docker’s health status, so the check has to mean something. Slim images often lack curl. If the image has Bash, Bash can open the socket itself:</p><pre>HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \<br>  CMD bash -c &#39;exec 3&lt;&gt;/dev/tcp/127.0.0.1/8080 &amp;&amp; printf &quot;GET /health/ready HTTP/1.0\r\nHost: localhost\r\n\r\n&quot; &gt;&amp;3 &amp;&amp; head -n1 &lt;&amp;3 | grep -q &quot; 200 &quot;&#39;</pre><p>/health/ready returns 200 only when the API can reach the database, so &quot;healthy&quot; means the release can serve real requests. With a 30-second interval, the first check lands about 30 seconds after start. On Docker 25 and later, --start-interval=2s checks faster during startup and makes the deploy gate quicker.</p><p>The frontend nginx image uses BusyBox wget against / on each site. That proves nginx is up and the built index.html is there.</p><h3>Two details that bite in production</h3><p><strong>Client IPs.</strong> Caddy connects to a port Docker publishes, so the API sees the Docker bridge gateway (something like 172.18.0.1) as every client&#39;s address. A per-IP login rate limiter then puts every user in one bucket, and one person hammering the login endpoint locks everyone out. In Express, app.set(&#39;trust proxy&#39;, 1) trusts exactly one hop and reads the real address from X-Forwarded-For. That&#39;s safe here because Caddy replaces any X-Forwarded-For a client sends unless you configure trusted proxies, and the loopback binding means nothing outside the box reaches the API except through Caddy.</p><p><strong>Build-time config in static frontends.</strong> Vite bakes VITE_API_URL into the bundle at build time, so changing the API&#39;s address means rebuilding the frontend image, not restarting it. The Dockerfile refuses to build without it rather than shipping a dashboard that calls undefined/api/...:</p><pre>ARG VITE_API_URL<br>RUN test -n &quot;$VITE_API_URL&quot; || (echo &quot;set --build-arg VITE_API_URL=https://&lt;your api&gt;&quot; &gt;&amp;2; exit 1)</pre><p>The frontend image is multi-stage. Node builds the sites, and the final stage is nginx-unprivileged with no Node in it. For the Vite dashboard, hashed files under /assets/ get Cache-Control: public, max-age=31536000, immutable, and index.html gets no-cache. Browsers revalidate it on every load, so a deploy reaches users on their next page load. Old hashed chunks disappear on deploy, so a tab left open across a deploy can 404 on a lazily loaded route until it&#39;s refreshed.</p><h3>The alternatives</h3><p><strong>Build on the server</strong> (git pull &amp;&amp; docker compose build). The most common first setup, and the one this pipeline exists to avoid. The server needs the full toolchain, and on a 2 GB box an npm ci or compile step competes with the live app for memory. There&#39;s no tested artifact, and rollback means rebuilding an old commit, which is slowest when you&#39;re under pressure. Building in CI is also what makes a $3 box viable.</p><p><strong>A managed PaaS: Render, Railway, Fly.io.</strong> You get deploy-on-push, TLS, logs and zero-downtime deploys without writing any of this. On Render, a deploy that fails its health check never goes live, so rollback is built in. The trade-off is price per service. Render’s cheapest always-on web service is $7/month with 512 MB, and its cheapest Postgres is $6/month with 256 MB: $13/month for one API and one database, with 768 MB of RAM between them, under 40% of a $3 slice. Railway and Fly.io bill by resource usage, which tracks load but is harder to predict. These win when several people deploy, when zero downtime matters, or when you don’t want to own a Linux box.</p><p><strong>Azure App Service.</strong> The Linux B1 plan is listed at about $13/month, for compute only. Deployment slots, the feature that gives App Service zero-downtime swaps, start at the Standard tier, not Basic. It wins if you’re already in Azure and willing to pay for Standard.</p><p><strong>A managed database</strong> such as Neon. Delete the postgres service and point the connection string at the provider. You stop owning backups, get point-in-time restore and branching, and free RAM on the box. Watch the interaction with your health check, though. Neon&#39;s Launch plan bills compute at $0.106 per compute-unit-hour with no monthly minimum, and it saves money by suspending idle computes. A Docker health check that queries the database every 30 seconds means it never idles. Even at a quarter of a compute unit, always-on comes to about $19/month, six times the VPS. If you go this way, point the HEALTHCHECK at a liveness endpoint that doesn&#39;t touch the database. Then have remote-deploy.sh curl 127.0.0.1:8081/health/ready once after the container is healthy, so the deploy gate still proves the database connection.</p><p><strong>Kamal, Coolify, Dokku.</strong> Self-hosted PaaS tools on your own VPS. Kamal closes the main gap in this setup: its proxy switches traffic to the new container only once it’s healthy, so deploys have no downtime. It wins once a few seconds of downtime per deploy starts to matter.</p><p><strong>Other CI/CD shapes:</strong></p><ul><li><strong>A self-hosted runner on the VPS for the deploy job only.</strong> Keep test and build on GitHub’s runners. The runner makes outbound connections to GitHub, so you can close port 22 to the internet. The costs are runner upkeep, and never using it on a public repository, where pull requests from forks could run code on your server.</li><li><strong>Pull-based deploys.</strong> An agent on the server polls the registry for new tags. CI never needs SSH, but you lose the “CI knows whether the deploy worked” loop unless you rebuild it.</li></ul><h3>What it costs</h3><ul><li>InterServer VPS, 1 slice (1 core, 2 GB RAM, 40 GB SSD, 2 TB transfer): $3</li><li>GitHub Actions: $0 within the free plan’s 2,000 private-repo minutes; unlimited on public repos</li><li>GitHub Container Registry: $0; container storage is currently free</li><li>Caddy + Let’s Encrypt: $0</li><li>Off-box backup storage for pg_dump files: ~$0–1 on object storage</li></ul><p><strong>Total: ~$3–4 a month</strong>, shared by every project on the box.</p><ul><li><strong>Scaling is a slice at a time.</strong> Each slice adds the same $3 of resources: 4 slices are $12 for 2 cores and 8 GB. Resize when steady-state usage in docker stats and free -m approaches your limits, not after an OOM kill. Repeated OOM kills with flat traffic usually mean a leak to fix, not a box to grow. docker inspect -f &#39;{{.State.OOMKilled}}&#39; &lt;container&gt; tells you which one it was.</li><li><strong>Actions minutes.</strong> Jobs are billed per job and rounded up to the minute, and the frontend and cleanup workflows draw from the same 2,000 minutes. At an assumed 10 minutes per deploy, that’s about 200 deploys a month. Check real run times in the Actions tab.</li><li><strong>GHCR.</strong> GitHub’s billing docs say container storage and bandwidth are free for now, with at least a month’s notice before that changes. The weekly prune to 10 versions is insurance for that day.</li></ul><h3>Where it falls short</h3><ul><li><strong>No automatic database backups.</strong> Until a cron job runs pg_dump and ships the file off the box, a lost disk means lost data.</li><li><strong>A few seconds of downtime per deploy.</strong> docker compose up -d stops the old container before the new one is healthy. Clients that reconnect cope; a checkout page wouldn&#39;t.</li><li><strong>Rollback restores code, not data.</strong> If migrations run at startup and a release applies one, the old code comes back against the new schema. Keep migrations backward-compatible, or run them as a separate step.</li><li><strong>The deploy key is effectively root.</strong> The deploy user is in the docker group, which is root-equivalent, so the SSH key in your GitHub secrets is root on the box. A forced command= in authorized_keys doesn&#39;t fix this as written. The workflow also copies the compose file over the same key, and a compose file can ask for privileged: true. Treat the key like a root password: one per server, rotated, and nowhere else.</li><li><strong>Port 22 is open to the world.</strong> GitHub’s runner IP ranges are too broad to allowlist usefully. Key-only login is the minimum; the self-hosted deploy runner above closes the port.</li><li><strong>The server’s registry login expires.</strong> The server pulls private images with a classic personal access token scoped to read:packages, tied to your account. Put its expiry in your calendar, or make the image public and skip the login.</li><li><strong>One box, one region.</strong> A hardware failure means downtime until you rebuild. Moving providers means new secrets, DNS changes and a pg_dump and restore, so keep the setup notes complete.</li><li><strong>You’re the ops team.</strong> OS updates, Docker upgrades and disk space are on you.</li></ul><h3>Takeaways</h3><ol><li><strong>Build in CI and deploy the commit SHA</strong>, never :latest and never on the server.</li><li><strong>Pull before you stop anything</strong>, gate on a health check that touches a real dependency, and roll back to whatever was running before.</li><li><strong>Check the public URL from outside</strong>, because healthy on loopback isn’t reachable by users.</li><li><strong>Bind containers to </strong><strong>127.0.0.1, put Caddy in front, pin the SSH host key</strong>, and keep secrets in a server-only .env.</li><li><strong>Start on one $3 slice, set memory limits that fit in RAM, and add slices on evidence.</strong> Schedule pg_dump on day one.</li></ol><p>When a few seconds of downtime per deploy starts to cost you, move to Kamal. You keep the same image and the same registry.</p><p><strong>Sources</strong></p><ul><li><a href="https://www.interserver.net/vps/">InterServer VPS pricing</a></li><li><a href="https://docs.github.com/en/billing/concepts/product-billing/github-packages">GitHub Docs: How use of GitHub Packages is measured</a></li><li><a href="https://docs.github.com/en/get-started/learning-about-github/githubs-plans">GitHub Docs: GitHub’s plans</a></li><li><a href="https://render.com/pricing">Render pricing</a></li><li><a href="https://neon.com/pricing">Neon pricing</a></li><li><a href="https://azure.microsoft.com/en-us/pricing/details/app-service/linux/">Azure App Service on Linux pricing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146ae9deaa11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I swapped my speech recogniser for GPT. My evals say it wasn't that simple]]></title>
            <link>https://medium.com/@okoliryan50/i-swapped-my-speech-recogniser-for-gpt-my-evals-say-it-wasnt-that-simple-8203eb1b6389?source=rss-1e470bd66360------2</link>
            <guid isPermaLink="false">https://medium.com/p/8203eb1b6389</guid>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Ugochukwu Okoli]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 12:42:05 GMT</pubDate>
            <atom:updated>2026-10-26T12:45:08.012Z</atom:updated>
            <content:encoded><![CDATA[<p>If you practise IELTS Speaking alone, the mark you get is only as good as the transcript the marker reads. I built a mock examiner that talks to you, records your answers and marks you on the four criteria (Fluency and Coherence, Lexical Resource, Grammatical Range and Accuracy, and Pronunciation). The hard question turned out to be a different one: how much of the transcript can you trust?</p><p>The short version: I started with the browser’s free speech recogniser and moved to GPT’s transcription model because the browser kept getting me wrong. Later I wrote evals to check whether that helped. It helped less than I assumed. In my test run the new model quietly fixed some of the grammar it was supposed to preserve, and the app still uses that model by default. Picking a different model didn’t fix it either. What helped was comparing the two transcripts and telling the marker where they disagree, which catches some of the tidying, not all of it. The examiner and marker run on OpenAI or Claude; audio transcription is OpenAI-only.</p><p>The code is at <a href="https://github.com/Okoli-Ryan/ielts-speaking-coach">Okoli-Ryan/ielts-speaking-coach</a>.</p><figure><img alt="The Exam tab: a target band slider, a model picker and a Begin test button" src="https://cdn-images-1.medium.com/max/800/0*BjUdbmGF2egz_Sk9.jpg" /></figure><h3>Version one: the browser’s recogniser</h3><p>The first version used the Web Speech API. It is free and instant, and it streams words as you speak, which is what turn-taking needs: when you stop talking, the examiner asks the next question. The marker received that text.</p><p>It was often wrong. The transcript is the only evidence the marker gets, so a misheard word is not a cosmetic problem. A garbled sentence drags down Pronunciation, Lexical Resource and Grammatical Range for reasons that have nothing to do with how you spoke.</p><h3>The trap on the other side</h3><p>The obvious fix is to clean the transcript up. That breaks something else.</p><p>IELTS marks your errors. “I am work as a developer” is evidence for Grammatical Range, and it should cost you. If a correction step turns it into “I am working as a developer”, your mark rises on a mistake you really made, and the practice feedback is worth nothing.</p><p>So any cleanup has to fix the recogniser’s mistakes and leave yours alone. I wrote that rule into the repair prompt as a hard constraint, with examples:</p><pre>NEVER FIX (these belong to the candidate and are being assessed):<br>- Grammar of any kind. &quot;I am work as a developer&quot; stays exactly as it is. &quot;because is cheaper&quot;<br>  stays. &quot;I have went&quot; stays. &quot;he don&#39;t like&quot; stays.<br>- Verb tense, agreement, articles, plurals, prepositions, word order.<br>- Word choice, collocation or register, even when it is clearly wrong or unnatural.<br>- Repetition, self-correction, false starts, hesitation and filler words.<br>- Incomplete or abandoned sentences.<br>- Anything you merely suspect might be a mis-hearing. If a reading is grammatically wrong but<br>  acoustically plausible as spoken, it is the CANDIDATE&#39;S error - leave it.</pre><p>The subtler case is a fix that drags the grammar along with it. If the recogniser hears “many receipt” and the speaker said “many recipe”, the repair must produce “many recipe”, not “many recipes”. The wrong singular after “many” is the speaker’s. The <a href="https://github.com/Okoli-Ryan/ielts-speaking-coach/blob/6cd539f2d62f0262db70e331d72f7dee88c92288/server/prompts.js#L233-L274">full prompt</a> spells that out.</p><h3>Version two: let a model listen to the audio</h3><p>Each answer is also recorded as audio, so a speech-to-text model can read the recording instead of the browser’s text. The call is small:</p><pre>export async function transcribeAudio(<br>  client,<br>  audio,<br>  { mime = &quot;audio/webm&quot;, model = transcribeModel(), prompt = TRANSCRIBE_PROMPT } = {}<br>) {<br>  const type = mime.split(&quot;;&quot;)[0].trim();<br>  const file = await toFile(audio, `answer.${EXTENSIONS[type] ?? &quot;webm&quot;}`, { type });<br>  const result = await client.audio.transcriptions.create({<br>    file,<br>    model,<br>    language: &quot;en&quot;,<br>    prompt,<br>    response_format: &quot;text&quot;,<br>  });<br>  return (typeof result === &quot;string&quot; ? result : result.text ?? &quot;&quot;).trim();<br>}</pre><p>The prompt is where I asked the model for a verbatim transcript. Speech models tend to tidy speech into fluent prose, so the prompt tells it not to:</p><pre>export const TRANSCRIBE_PROMPT = `Transcribe exactly what the speaker says, word for word.<br>This is a language exam recording and the speaker&#39;s errors are the object of assessment.<br>Preserve grammatical mistakes, wrong verb tenses, missing articles, wrong plurals, false starts,<br>repetitions and filler words such as um, uh and er. Do not correct, tidy, complete or paraphrase<br>anything. Write only what was actually said.`;</pre><p>The prompt asks for verbatim output. Whether the model obeys it is a separate question.</p><h3>Checking it: the evals</h3><p>The model calls that decide a mark are transcribing, repairing and marking. They live in one module, <a href="https://github.com/Okoli-Ryan/ielts-speaking-coach/blob/6cd539f2d62f0262db70e331d72f7dee88c92288/server/core.js">server/core.js</a>, so the app and the evals run the same code. Each of the three has its own eval, and a fourth came later.</p><p>The repair eval uses eleven fixtures (hand-written test transcripts), each with mistakes planted on both sides: some the recogniser made (<em>receipt</em> for <em>recipe</em>, <em>bang</em> for <em>bank</em>) and some the candidate made (<em>I am work</em>, <em>two book</em>). A fix has to land, and every candidate error has to survive:</p><pre>const guards = [<br>  ...(fixture.mustKeep || []).map(asKeep).map((k) =&gt; ({<br>    label: `keeps &quot;${k.phrase}&quot;`,<br>    pass: containsPhrase(corrected[k.turn] ?? &quot;&quot;, k.phrase),<br>  })),<br>  ...(fixture.forbid || []).map((phrase) =&gt; ({<br>    label: `never writes &quot;${phrase}&quot;`,<br>    // Per turn, so a phrase cannot match across the join between two turns.<br>    pass: corrected.every((text) =&gt; !containsPhrase(text, phrase)),<br>  })),<br>];</pre><p>The two checks aren’t weighted equally. A missed mis-hearing is a quality problem, so it is a soft check with a 75% floor. A touched candidate error makes the mark untrustworthy, so it fails the run.</p><p>An eval that passes everything has not shown it can measure anything, so I kept a negative control: a deliberately naive prompt.</p><pre>export const NAIVE_REPAIR_PROMPT = `Fix any mistakes in this transcript of a spoken English exam.<br>Correct spelling, grammar and wording so the text reads naturally. Report every change.`;</pre><p>On the same fixtures the real prompt preserved 100% of candidate errors and changed none of the four transcripts that needed no change. The naive prompt preserved 27.8% and rewrote two of those four. One run per prompt on fixtures I wrote myself is enough to show the eval can tell the two apart, not to put a number on the real prompt. And the naive prompt fails in exactly the direction that matters: it fixes the candidate’s grammar.</p><p>The marker eval uses three answers to one question, written to sit at weak, middle and strong levels. They should rank in that order, and they did: 5.5, 7 and 7.5 on the default model. That is one sample per answer, so a half-band difference is inside the noise. The second check chains repair into marking: take the middle answer, garble it by hand the way a recogniser would, repair it and mark it. Garbling cost half a band (7 to 6.5), and the repaired version came back to 7 and no higher. With one sample the check tolerates half a band, so it rules out a big inflation, not a small one.</p><p>I also marked a grammar-tidied copy of the weak answer, expecting a big jump. Grammatical Range moved from 5 to 5.5 and the overall band did not move. That is one sample and a half-band step, so it is within noise. The repair guard exists because the risk is real, not because I measured an effect.</p><p>The transcription eval is different: the marker and repair evals run on text, and this one needs real audio. I added a <a href="https://github.com/Okoli-Ryan/ielts-speaking-coach/blob/6cd539f2d62f0262db70e331d72f7dee88c92288/public/capture.js">capture page</a> that records you reading ten scripted lines and saves two things side by side: your audio, and what the browser’s recogniser heard while you spoke. The lines carry planted learner errors (“I have went”), fillers (“um”, “er”) and mis-hearing traps (“recipe”, “colleague”).</p><figure><img alt="The capture page listing the ten lines to read, each marked as recorded" src="https://cdn-images-1.medium.com/max/800/0*d3NiiKzNZbvchEa5.jpg" /></figure><p>The audio goes to gpt-transcribe, the browser text is already saved, and both are scored against the script on three measures: word error rate (the words the transcript dropped, added or swapped, as a share of the words in the script), how many planted learner errors survived, and how many fillers survived. The second and third matter more than the first. A transcript with a low word error rate that has quietly fixed your grammar is worse for marking than a noisy one.</p><h3>The result I didn’t expect</h3><p>I recorded the ten clips myself, with the recogniser set to British English.</p><pre>Browser   gpt-transcribe<br>Mean word error rate   6.1%      6.5%<br>Learner errors kept    8 of 11   8 of 11<br>Fillers kept           2 of 4    0 of 4</pre><p>gpt-transcribe did not beat the browser. Word error rate was within half a point (6.5% against 6.1%), learner errors kept were identical (8 of 11), and the browser kept more of the fillers. One caveat on that last number: one of the browser&#39;s two kept fillers was an &quot;er&quot; it heard as &quot;uh&quot;, and the scorer counts any filler. The run failed my hard check, because 8 of 11 is below the 90% floor I set.</p><p>The per-clip rows show how the two differ. On clip 1, I read: “I am work as a software developer in a small company. Um, I have went there since three years.”</p><pre>Browser:        I am work as a software developer in a small company. There since three years.<br>gpt-transcribe: I am work as a software developer in a small company. I have worked there since three years.</pre><p>The browser lost words; gpt-transcribe changed them, turning <em>went</em> into <em>worked</em>. A gap at least looks like a gap to a human reading the transcript. A corrected verb reads fine, and nothing tells the marker it was ever wrong.</p><p>gpt-transcribe tidied other things too: &quot;cook many recipe&quot; came back as &quot;cooked many recipes&quot;, and the repeated &quot;to, to Japan&quot; lost its repetition. On clip 4 it also cut the sentence off before &quot;delicious&quot;. On the filler clip it removed every &quot;uh&quot; and &quot;er&quot; even though the recording has them. For Fluency and Coherence that is a loss, because hesitation is evidence.</p><h3>Is there a setting for this?</h3><p>I went looking for a switch. <a href="https://developers.openai.com/api/docs/guides/speech-to-text">OpenAI’s speech-to-text guide</a> has no verbatim or filler option for gpt-transcribe. The only lever is prompt, which the guide describes as context about the recording, with preserving filler words as one listed use. The model also takes a keywords list.</p><p>Other providers do expose a switch. <a href="https://www.assemblyai.com/docs/pre-recorded-audio/include-filler-words">AssemblyAI</a> has disfluencies, which defaults to false, so fillers are stripped unless you turn it on. <a href="https://ai.google.dev/gemini-api/docs/transcribe">Google&#39;s Gemini transcription</a> has a verbatim mode that keeps hesitations and false starts, and a smart mode that removes them, according to its docs. I haven&#39;t tested either on my clips, so I can&#39;t say how well they keep what I said. One <a href="https://arxiv.org/pdf/2503.06924">benchmark on non-native English</a> (22 speakers, 157 fillers, 40 repetitions) found AssemblyAI detected about 99% of fillers but kept only about a fifth of repetitions, while Deepgram kept most repetitions but detected about 71% of fillers. That is one small dataset, so treat it as a reason to test, not a ranking.</p><h3>Trying the options I could run</h3><p>The OpenAI options were cheap to try with the eval, so I ran each on the same ten clips, once each.</p><pre>Option                                                        Word error rate   Learner errors kept   Fillers kept<br>Browser                                                       6.1%              8 of 11               2 of 4<br>gpt-transcribe, my original prompt                            6.5%              8 of 11               0 of 4<br>gpt-transcribe + a prompt written as a verbatim example       6.5%              8 of 11               0 of 4<br>gpt-transcribe + keywords for um, uh, er, erm                 6.5%              8 of 11               0 of 4<br>gpt-transcribe + the hint phrased as context, plus keywords   6.0%              9 of 11               0 of 4<br>gpt-4o-transcribe                                             10.4%             9 of 11               0 of 4<br>whisper-1 + a prompt written as a verbatim example            5.6%              9 of 11               3 of 4</pre><p>The first three gpt-transcribe variants gave nearly the same text. Phrasing the hint as context was the one gpt-transcribe variant that kept &quot;I have went&quot; on clip 1. One extra kept error in one run is within noise, but it is the cheapest thing to retest. On the verbatim-example prompt, nine of ten clips came back identical and the tenth differed by a comma. Swapping in gpt-4o-transcribe kept one more learner error and lost accuracy elsewhere: one clip came back as &quot;I mean, I would like to travel to Japan&quot;, a 55% word error rate.</p><p>whisper-1 was the exception. With a few lines of hesitant, error-filled speech as its prompt, it kept &quot;Um, I have went there since three years&quot; word for word, and it kept the &quot;er&quot;s in the filler clip. It also misheard words that gpt-transcribe got right, writing &quot;the sheep live&quot; for &quot;the ships leave&quot;, and it still turned &quot;cook many recipe&quot; into &quot;cooked many recipes&quot;. OpenAI&#39;s <a href="https://developers.openai.com/api/docs/guides/speech-to-text">speech-to-text guide</a> lists it as deprecated, with a shutdown date in February 2027. One caveat on its 3 of 4: the scorer counts any filler, and on the filler clip it wrote &quot;er&quot; where I said &quot;uh&quot;. No option kept every learner error.</p><h3>Telling the marker where the transcripts disagree</h3><p>Neither transcript is reliable alone, but they fail differently. Where the browser and the audio model agree, the text is probably right. Where they disagree, one of them changed what I said, and nothing in either text says which. The marker should be told.</p><p>So the app now compares the two transcripts of each answer word by word, groups the differences, and sorts each one:</p><pre>let kind = &quot;changed&quot;;<br>if (browser.length &amp;&amp; !audio.length) {<br>  kind = browser.every((w) =&gt; FILLERS.has(w)) ? &quot;filler-dropped&quot; : &quot;missing-in-audio&quot;;<br>} else if (!browser.length) {<br>  kind = &quot;missing-in-browser&quot;;<br>}</pre><p>The <a href="https://github.com/Okoli-Ryan/ielts-speaking-coach/blob/27c9fb86f00dba462f7d5412db01ca5e0cabb76c/public/align.js#L59-L100">full aligner</a> is about forty lines. The marker then gets a short note per disagreement, for example that the browser heard “cook” where the audio model wrote “cooked”, and a new instruction: don’t award or deduct marks for grammar or vocabulary at those spots, and never quote them as evidence. It treats a filler the audio model dropped as a possible hesitation and says so.</p><p>That fourth eval runs on the clips I’d already recorded, with no API calls. A tidying is a scripted learner error or filler that the audio model lost. If the browser still has it, the transcripts disagree there, so it should be flagged. Four of the seven tidyings were in that category and all four were flagged. As a negative control, a stub that never reports a disagreement caught none, so the test isn’t passing by default.</p><p>The other three show what this can’t catch. On those, the browser and the audio model both lost the words: my “um” on two clips and “I have went” on clip 1. Two systems agreeing on the wrong text looks identical to two systems agreeing on the right text, so no comparison sees it. For fillers that still needs a better source, which is why the whisper-1 row interests me and the providers with a filler switch are the next thing I&#39;d test.</p><p>I ran the marker once by hand with a note in place on a short answer. It marked normally and didn’t quote the flagged word. I haven’t run a full exam with a microphone through the new path.</p><h3>What the numbers do and don’t say</h3><p>This is ten clips from one speaker, one run each. It is enough to show the verbatim prompt doesn’t hold for my voice. It is not enough to rank the systems in the table, and a half-point gap in word error rate could be run-to-run noise, as could a one-error difference in learner errors kept. I have not repeated the runs.</p><p>There is also a flaw in the method. The script is the ground truth, not what I said. Reading “I have went” aloud without smoothing it to “I have gone” is harder than it sounds, so some misses may be mine. The result files keep the script, the browser text and gpt-transcribe&#39;s text for every clip, so you can see exactly which words each one changed. Only I can check them against the audio.</p><p>So the design question changed. I assumed that replacing the browser’s text with GPT’s would produce a better transcript for marking. For word accuracy it didn’t, and for the two properties a marker depends on, kept errors and kept hesitation, neither system was reliable. What I built instead of picking a winner is the comparison above. What I haven’t solved is the case where both transcripts lose the same words.</p><h3>Run it on Claude, or any other provider</h3><p>The experiments above all ran on OpenAI models, but the app doesn’t need to. Every model call (the examiner’s questions, the question papers, the marker, the repair pass) goes through a small provider interface in server/providers/. Two providers ship with it: OpenAI, and Anthropic&#39;s Claude.</p><p>To switch, put ANTHROPIC_API_KEY (or OPENAI_API_KEY, or both) in .env. The model picker in the header groups models by provider and greys out any model whose provider has no key, with the reason in its tooltip. It also greys out any model your key can&#39;t reach, which the server finds by listing each provider&#39;s models the first time the page loads:</p><pre>return catalog.map((m) =&gt; {<br>  const provider = byId.get(m.provider);<br>  const base = { ...m, providerLabel: provider?.label ?? m.provider };<br>  if (!provider?.configured()) {<br>    return { ...base, available: false, reason: `Set ${provider?.keyEnv ?? &quot;its API key&quot;} in .env to enable` };<br>  }<br>  const ids = reachable.get(provider.id);<br>  // A listed dated snapshot (id-YYYYMMDD) counts as reaching the alias.<br>  const listed = ids &amp;&amp; [...ids].some((id) =&gt; id === m.id || id.startsWith(`${m.id}-`));<br>  return ids &amp;&amp; !listed<br>    ? { ...base, available: false, reason: &quot;Your key cannot reach this model&quot; }<br>    : { ...base, available: true, reason: null };<br>});</pre><p>The first model whose provider has a key becomes the default, so a Claude-only setup opens on Claude, unless DEFAULT_MODEL in .env names another. The <a href="https://github.com/Okoli-Ryan/ielts-speaking-coach/blob/e3a36e02d4e214df9718bb14a1573484337242b6/server/models.js#L112-L141">full function</a> also times out a hung listing, so a slow network can&#39;t leave the page waiting.</p><p>Adding a provider takes one file that exports a factory returning { id, label, keyEnv, configured(), listModels(), parse(), stream() }, one line in the provider list in <a href="https://github.com/Okoli-Ryan/ielts-speaking-coach/blob/e3a36e02d4e214df9718bb14a1573484337242b6/server/providers/index.js">server/providers/index.js</a>, and its models in the model list in server/models.js. The dropdown, the availability checks and the evals read only those two lists.</p><p>There are two limits. Anthropic has no speech-to-text model, so audio re-transcription stays OpenAI-only. With only a Claude key the app marks from the browser’s transcript and switches that option off. The second is how much I’ve tested. I wrote the Claude path without an Anthropic key, so it first ran against a stand-in SDK in the test suite. Once I had a key I ran Claude Sonnet 5.5 through the app (examiner turns, question papers, cue cards), and ran Sonnet 5.5, Opus 5.5 and Haiku 5.5 through the repair and marker evals, once each. All three kept every planted candidate error. Opus fixed every planted mishearing, like GPT-5.6 Sol; Sonnet fixed 87.5% and Haiku 75%, which is the floor, and both missed “college” for “colleague”. All three ranked the marker answers in order, and all three marked at or below GPT-5.6 Sol on every answer. On the weak, mid and strong answers, GPT-5.6 Sol gave 5.5, 7 and 7.5, Opus 5, 6.5 and 7.5, Sonnet 4.5, 6 and 7, and Haiku 5, 6 and 7. With one sample each, half a band is inside the noise. Claude Fable 5.1 has not been run at all. A band from one model tells you nothing about another until you’ve checked, and these commands are how:</p><pre>npm run eval -- marker --model claude-sonnet-5-5<br>npm run eval -- repair --model claude-sonnet-5-5</pre><h3>Try it on your own voice</h3><pre>npm install<br>cp .env.example .env    # add OPENAI_API_KEY (the transcription eval needs it)<br>npm start               # open http://localhost:5173/capture.html and read the ten lines<br>npm run eval -- transcribe</pre><p>The recorder keeps your audio local and git-ignored. Run it with your own accent and your recogniser’s language setting. The transcription eval calls OpenAI’s speech model even if you examine and mark with Claude.</p><h3>Conclusion: what carries over</h3><p>I switched to a better-sounding transcription model expecting a cleaner transcript. The evals showed it was clean in the wrong way. It kept no more of my errors than the browser did, and where it lost one, it rewrote it into correct English instead of leaving a gap.</p><p>Decide what the transcript has to preserve before you measure how accurate it is: word error rate was within half a point between the two systems, and it said nothing about the property that mattered. Treat a prompt that asks for verbatim output as a request, not a guarantee. Mine didn’t stop the tidying, rewording it didn’t either, and only an eval on real audio showed it. When two imperfect sources fail differently, compare them: telling the marker where they disagree caught four of the seven tidyings, and the other three show where that stops. And give every eval a negative control, so you know it can fail.</p><p>All of this is ten clips from one speaker, so take the method, not the numbers. The repo runs the same checks on your voice. The transcription eval needs an OpenAI key; the marker and repair evals run on either provider. If your numbers disagree with mine, open an issue with your evals/results/transcribe.json.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8203eb1b6389" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Watch Party for Any Video on the Web]]></title>
            <link>https://medium.com/@okoliryan50/building-a-watch-party-for-any-video-on-the-web-30e047bd19be?source=rss-1e470bd66360------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e047bd19be</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Ugochukwu Okoli]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 09:31:01 GMT</pubDate>
            <atom:updated>2026-10-10T09:41:46.225Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I turned “a video element answers to JavaScript” into a browser extension that syncs films between friends, with no server and no player API</em></p><p>For a long time my friends and I watched films together on a third-party streaming site that had a watch-party feature built in. One person pressed play, and everyone’s player started. Then the site was shut down, and our watch parties went with it. The alternatives weren’t great. Screen sharing turns the film into a compressed video call, and the party features some platforms ship only work on that platform’s own catalogue.</p><p>So I decided to build my own to use with friends, with one extra goal: it shouldn’t care which site the film is on.</p><p>The idea seemed simple. Almost every streaming site plays through an HTML5 &lt;video&gt; element, and a &lt;video&gt; element answers to JavaScript. You can read its position, listen for play and pause, and set its time. If one browser could report what its video was doing, and a realtime service could relay that to everyone else in a room, every other browser could make its own video do the same.</p><p>The idea held up. Most of the work was in the gap between “a video answers to JavaScript” and “two friends’ browsers agree on what’s happening.”</p><p>The result is <a href="https://github.com/Okoli-Ryan/watchparty-extension">WatchParty Sync</a>, a Manifest V3 browser extension for Chrome, Edge and Firefox. A host picks a video on any page, friends join the room, and their players follow the host’s play, pause and seek. Firebase Firestore is the only backend. What follows are the questions I had to answer along the way. <a href="https://github.com/Okoli-Ryan/watchparty-extension/blob/main/DECISIONS.md">DECISIONS.md</a> in the repo has the longer reasoning behind each one.</p><figure><img alt="The whole flow at 4x speed: the host picks a video and creates a room, a friend joins from a second browser, and both players follow the host’s play, pause and seek." src="https://cdn-images-1.medium.com/max/720/0*NNACACp3EwICaSKQ.gif" /></figure><p><em>The whole flow at 4× speed: picking a video, creating a room, a friend joining, and both players staying in step. </em><a href="https://github.com/Okoli-Ryan/watchparty-extension/blob/main/docs/media/00-host-and-viewer-in-sync.mp4"><em>Watch the full walkthrough at normal speed</em></a><em> (1 min 45 s).</em></p><h3>Getting hold of the video</h3><h4>Why a browser extension, and not a website or a bookmarklet?</h4><p>Because of iframes. Streaming sites routinely load the real player from a different domain inside an iframe. Script running on the page, including a bookmarklet, is stopped at that boundary by the same-origin policy: it can see the frame but not the video inside it. A browser extension can inject its script into every frame on a page, cross-origin ones included. That one capability decided the platform.</p><h4>How does the extension know which video I mean?</h4><p>A page can hold the film, a muted ad loop and a few hover previews. My first version let you click the video you wanted, using a transparent overlay to catch the click. On the sites I cared about, that overlay sat on top of the iframe holding the real player and swallowed the very click it was waiting for.</p><p>So picking became a keyboard interaction. A banner appears, the arrow keys step through the page’s videos, Enter confirms and Escape cancels. Nothing the picker draws accepts the mouse, so the page stays usable underneath.</p><p>The videos are offered in order of likelihood. Bigger ranks higher, being loaded and playing count for a lot, and anything under 30 seconds is probably an ad and drops down the list. Playing counts for so much that the banner asks you to press play before picking. That also helps with players that don’t create a &lt;video&gt; element at all until playback starts.</p><figure><img alt="The keyboard picker on a YouTube page. The banner reads “Video 1 of 1 · 706×397 · 9:24” and asks you to start the video first, and a purple outline marks the player it will sync." src="https://cdn-images-1.medium.com/max/900/0*z8KjVEhj8idDwF1f.png" /></figure><h4>What if the video sits in a different frame from the one that has focus?</h4><p>Each frame runs its own copy of the extension’s script and can only see its own videos. Key presses only reach whichever frame has focus, and that might be an ad. No single frame can own the selection.</p><p>So every frame reports its candidates to the extension’s background, which merges them into one ranked list and tells each frame what to highlight. Every frame also listens for key presses and forwards them, including frames with no video at all, because focus might be sitting in one of them.</p><h4>How does my friend’s browser find the same video?</h4><p>When you confirm a pick, the room stores three things. The first is the page URL, the top-level one, since that’s where your friend’s tab gets sent. The second is a CSS selector for the video. The third is the origin of the frame the video lives in. It stores the origin rather than the frame’s full URL because embed URLs usually carry a session token, and your friend’s copy of the page will load its own.</p><p>Streaming sites rebuild their players often enough that selectors break. When the stored selector doesn’t match, the extension waits up to ten seconds and then falls back to the best-ranked video on the page, using the same ranking as the picker.</p><figure><img alt="The popup’s New room form after a pick: the room name, Public visibility, and a card showing the page URL, the generated video selector (.video-stream) and the 0:17 start time." src="https://cdn-images-1.medium.com/max/421/0*QCMNx4rxs35jIpho.png" /></figure><h3>Inside the extension</h3><h4>Why split the work across three parts of the extension?</h4><p>A Manifest V3 extension runs as several separate programs, and each has a blind spot.</p><ul><li>The content script lives inside the web page, so it can control the video. It runs in the page’s origin, though, so it can’t see the extension’s login.</li><li>The popup can hold the login, but it’s destroyed the moment it loses focus, which happens every time you click back into the film.</li><li>The background service worker survives the popup, but the browser suspends it when it’s idle, and it has no localStorage.</li></ul><p>So each does one job. The content script only touches the page. The background owns everything realtime: database subscriptions, playback updates and presence. The popup is for signing in and finding rooms. Every message between them is defined in one file, which is the first thing I’d tell anyone to read.</p><h4>How do the popup and the background share one login?</h4><p>Firebase normally keeps its session in localStorage, which a service worker doesn&#39;t have. Both the popup and the service worker can use IndexedDB, and because they run at the same chrome-extension:// origin, they see the same stored session. Switching Firebase to IndexedDB persistence was a one-line change. You sign in once in the popup, and the background uses that session.</p><h4>How would I handle persistence across tabs and restarts?</h4><p>This took more care than anything else, because there are four ways to lose a session.</p><ul><li><strong>The popup closing.</strong> Nothing lives there, so nothing is lost.</li><li><strong>The service worker being suspended.</strong> While you’re in a room, the page sends the background a small heartbeat every three seconds over a long-lived connection called a port. Since Chrome 114, each message on a port resets the worker’s 30-second idle timer, so it stays awake. If it restarts anyway, the room session is saved in session storage and rebuilt on startup.</li><li><strong>The tab navigating.</strong> Joining a room sends your tab to the host’s page, which tears down the old page’s connection. At first the extension read that as you leaving the room. It now marks those navigations as intentional and reattaches when the new page checks in.</li><li><strong>Frames coming and going.</strong> A tab has many frames, and ad frames load and unload constantly. Connections are tracked per frame (my first version tracked them per tab, so each new frame overwrote the last), and only the frame holding the video counts as leaving.</li></ul><p>Personal state, like which rooms you’ve watched and your favourites, lives under your user in the database rather than in the browser. It follows you to other machines and to the web dashboard.</p><h3>Keeping playback in sync</h3><h4>Why sync only when the host acts, instead of constantly?</h4><p>Because constant correction is worse than small drift. Every forced seek fights the viewer’s own buffering, and on a slow connection that makes the film stutter. A viewer realigns only when the host plays, pauses, seeks or changes speed, or when someone new joins. Even then the player only jumps if it’s more than two seconds out. Being a second behind is invisible, and a stutter every few seconds isn’t. For a viewer who has drifted anyway, there’s a <strong>Sync with host</strong> button.</p><p>The trade-off is that nothing is ever sent twice. If an update goes missing, it stays missing until the host does something else. Both of the worst bugs I hit came from that.</p><h4>How do you stop the host’s player echoing changes back?</h4><p>Applying a remote pause makes the video fire its own pause event, which could be published as a brand-new host action. Two guards prevent the loop. Viewers never publish anything. And when a host applies state, which happens when they return to a room that’s already mid-film, the extension ignores the events it caused itself for the next 800 ms, long enough for playback and seeks to settle.</p><h4>Dragging the timeline fires dozens of seek events. How do you handle that?</h4><p>Seek updates are throttled to one every 150 ms. My first version simply dropped the extras, and the last seek of a drag, the one that matters, nearly always landed inside the throttle window. Everyone was left where the host had been mid-drag. The throttle now holds on to the latest seek and sends it when the window ends.</p><h4>What can we do about browsers blocking autoplay?</h4><p>Browsers block unmuted playback until you’ve interacted with the page, and a viewer who’s just joined hasn’t. When a viewer arrives, the extension shows a “Click to start watching together” button and tries to play straight away. If the browser refuses, it retries muted, which browsers allow, and offers an unmute button. If even that fails, it waits for the click.</p><figure><img alt="A viewer’s tab right after joining a room: the film is paused and a “Click to start watching together” button sits below the player." src="https://cdn-images-1.medium.com/max/1024/0*eCwEup4R1H9Gf4J3.png" /></figure><h4>What happens when someone joins halfway through the film?</h4><p>This was the first bug that changed the design. A friend joined 40 minutes in, and their player started from the beginning and stayed there until the host happened to pause.</p><p>Joining sends the viewer’s tab to the film’s page, and the first update from the database almost always arrived before the new page was ready to receive it. The background sent the host’s position to a page that wasn’t there yet, but recorded it as delivered, so it skipped every later update carrying the same position. The message that attaches the player also carried the host’s state, but the player ignored it unless you were the host.</p><p>The fix became a rule I now apply everywhere: in a system that never resends, only count something as delivered once it actually arrived. Once the viewer’s player is found, the background also sends a fresh resync, moved forward by however old the host’s last update is.</p><h4>How can a viewer be “in sync” and still seconds ahead?</h4><p>That was the second bug. <strong>Sync with host</strong> worked out where the host should be from their last action: if they pressed play at 100 seconds a minute ago, they should be at 160. But if the host’s player stalled for six seconds to buffer during that minute, they’re really at 154. A buffering stall doesn’t fire a pause event, so nothing was published. The viewer hadn’t stalled, sat at 160, matched the calculation exactly, and was told “already in sync” while six seconds ahead. After an hour with no host actions, the calculation was an hour old.</p><p>The fix gives resync a second reference point. The host’s real position rides along on the heartbeat, and the background writes it to the room alongside the liveness update it already makes every nine seconds or so. Viewers ignore it during normal playback. Only a resync reads it, and it uses whichever reference is newer.</p><p>Reviewing that fix while writing this article turned up two mistakes in it. The position was stamped with the time it was written rather than the time it was read, up to three seconds later, so resync could pull an in-sync viewer backwards. And only heartbeats refreshed it, so a write landing just after a seek recorded the pre-seek position with a newer timestamp. Both are fixed now: the position records when it was read, and every host action refreshes it.</p><figure><img alt="The viewer’s expanded widget: role VIEWER, the host’s name, 2 watching, state paused, and the Sync with host, Chat, Dashboard and Leave room buttons." src="https://cdn-images-1.medium.com/max/285/0*X97Uis1X20xx2SB6.png" /></figure><h3>Running with no server</h3><h4>Why Firebase, and why no backend of my own?</h4><p>I wanted something friends could use without me running a server. Firestore gives realtime subscriptions, authentication, and a free tier that comfortably covers a few rooms. With no server, the database’s security rules are the entire security model: who can read rooms, who can change playback, who can delete a chat message.</p><h4>How does the extension know who’s still in the room?</h4><p>Each member writes a heartbeat to the database every three seconds, and anyone more than ten seconds behind is treated as gone. The first version compared those server timestamps with each browser’s own clock. A host whose clock ran fast judged <em>itself</em> stale within ten seconds, removed itself and killed the room. Now each browser estimates the gap between its clock and the server’s from the newest heartbeat, and measures freshness against that estimate. The rule I wrote down after the bug came back a second time: never compare a server timestamp with the local clock.</p><p>The background writes these heartbeats, not the page. Chrome throttles timers in hidden tabs to about once a minute, and a viewer who switched tabs would otherwise drop out of the room.</p><h4>Who’s in charge when the host leaves?</h4><p>Ownership is two fields. One says who is driving playback right now. It moves automatically when the host leaves or crashes, to the original host if they’re still around and otherwise to whoever joined earliest. The other records who holds the room, and only moves when the host deliberately hands it over. With that split, a host who refreshes the page gets their room back, and a deliberate handover sticks.</p><p>One more guard was needed. The database’s first answer after you join comes from the local cache, which only contains your own entry. Treating that as the truth made every new viewer promote themselves to host, so ownership decisions now wait for a confirmed answer from the server.</p><h4>How do rooms end if nobody closes them?</h4><p>A crashed browser can’t mark its room as ended. So a room counts as live only while its host keeps writing a liveness timestamp, and drops off the list once that’s 30 seconds old. A clean exit ends the room immediately, and a crash ends it on its own.</p><h4>How is chat kept private?</h4><p>Messages are encrypted in the background before they reach the database, so the database only ever holds ciphertext. Public rooms keep a random key on the room itself, which makes joining one click, but means someone with database access could decrypt them. Private rooms derive the key from a passphrase that’s never stored anywhere. Not even I, as the project owner, can read those. If the passphrase is lost, so is the chat.</p><h3>What I’d improve</h3><h4>Should it move off Firebase?</h4><p>Probably, and the reasons are mostly the workarounds above. Firebase made it possible to ship without a server, but several of the hardest problems came from having no authority in the middle.</p><ul><li><strong>Clocks.</strong> Every browser estimates the server’s time from heartbeats. A server could stamp every event with one clock.</li><li><strong>Presence.</strong> A heartbeat write every three seconds per viewer costs database reads and writes, and “gone” really means “ten seconds without a write.” A server sees a dropped connection directly.</li><li><strong>Ownership.</strong> Every browser runs the same handoff logic and has to avoid racing the others, and the rules let any signed-in user make themselves owner so that a stranded room can recover. A server could simply decide.</li><li><strong>Accounts.</strong> The rules stop non-admins creating user profiles, but anyone with the public config can still create a login unless sign-up is switched off in the console. A real endpoint closes that properly.</li></ul><h4>What would replace it?</h4><p>The shape that fits is one small stateful process per room, with every member holding a WebSocket open to it. Cloudflare Durable Objects, or PartyKit on top of them, give you exactly that without managing machines. A Node server with WebSockets, plus Redis to share state across instances, is the self-hosted version. Supabase Realtime is a managed middle ground with presence built in.</p><p>With a room server in the middle:</p><ul><li>The server stamps every playback event with its own clock, so the clock estimation goes away.</li><li>Presence comes from the connection itself, with a short grace period for reconnects, instead of heartbeat writes.</li><li>Ownership and handoff are decided in one place.</li><li>Chat stays encrypted in the browser. The server only relays ciphertext, so private rooms stay private.</li></ul><h4>How would I manage the migration?</h4><p>Most of the groundwork is already there. The content script and popup never talk to the database directly. Everything realtime goes through the background, and every database call lives in a handful of small modules. So the plan would be:</p><ol><li>Put an interface in front of those modules (join a room, publish playback, subscribe to room state, send a chat message) and move the Firebase code behind it.</li><li>Build the WebSocket version behind the same interface and switch rooms over with a flag, so both can run side by side while testing.</li><li>Keep the service worker awake the same way it is now. Since Chrome 116, WebSocket traffic counts as activity, so a ping every 20 seconds or so keeps an open connection from being suspended.</li><li>Move accounts and personal history last. Login can stay on Firebase for a while, with the room server checking Firebase’s tokens, until there’s a reason to move it too.</li></ol><p>The cost is real. You now run, monitor and pay for a server, and you own reconnection and scaling. For a handful of friends, Firebase is fine. For anything bigger, the server earns its keep.</p><h4>What else is on the list?</h4><ul><li><strong>Tests.</strong> The ranking, projection and presence logic is the code most likely to break and the easiest to test, and none of it has tests yet.</li><li><strong>Fewer permissions.</strong> The extension asks for access to every site, because a viewer’s tab is sent to the host’s page before they’ve clicked anything there. Asking per site when you create or join a room would be friendlier, and would make a store listing much easier.</li><li><strong>Rebuilt players.</strong> If a site swaps out its video element mid-film, the extension doesn’t notice, and sync quietly stops for that browser. Watching for that and reattaching would fix it.</li><li><strong>Fullscreen inside iframes.</strong> The on-page widget follows the page into fullscreen, but not when a player iframe goes fullscreen on its own.</li></ul><p>The idea I started with held up: a video element answers to JavaScript, and a realtime channel can keep many of them in step. The real work was in the edges, like frames, focus, clocks, and messages that arrive before anyone is ready for them. The code is on <a href="https://github.com/Okoli-Ryan/watchparty-extension">GitHub</a>, and <a href="https://github.com/Okoli-Ryan/watchparty-extension/blob/main/DECISIONS.md">DECISIONS.md</a> has the longer story behind each choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e047bd19be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a PR-review bot that actually maps to line numbers]]></title>
            <link>https://medium.com/@okoliryan50/building-a-pr-review-bot-that-actually-maps-to-line-numbers-052b3e3970da?source=rss-1e470bd66360------2</link>
            <guid isPermaLink="false">https://medium.com/p/052b3e3970da</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Ugochukwu Okoli]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 11:31:01 GMT</pubDate>
            <atom:updated>2026-08-18T11:47:33.241Z</atom:updated>
            <content:encoded><![CDATA[<p>Every team hits the same wall as it grows: code review becomes the bottleneck. Not because people don’t care, but because the reviewers who catch the subtle bugs (the SQL string concatenation, the await that quietly went missing, the null that can now reach a dereference) are the same people with the least time to read a 400-line diff at 6pm.</p><p>So it’s tempting to point an LLM at the problem. And the first attempt almost always looks like this: grab the diff, paste it into a chat model, ask “any bugs?”, copy the answer back into the PR. It sort of works. It also produces a wall of prose that doesn’t map to any line, mixes a security hole in with three complaints about naming, and confidently invents a problem on a line that wasn’t even changed.</p><p>The gap between that and something you’d actually let comment on a pull request is smaller than it looks, but it’s entirely made of unglamorous engineering: parsing the diff, pinning the model’s output to a schema, filtering the noise, and mapping every finding back to a real line so GitHub can anchor a comment to it. This post builds that, end to end, in a few hundred lines of TypeScript. The result is <a href="https://github.com/Okoli-Ryan/diff-sentry">diff-sentry</a>: a CLI and a GitHub Action that reviews a diff with Claude and posts structured findings.</p><p>We’ll also look at the dozen-odd platforms that already sell this, because for a lot of teams the right answer is to buy it. Knowing what the build involves is the best way to judge what you’re buying.</p><h3>Why “paste the diff into a chat model” falls short</h3><p>Four problems, each of which the rest of this post is really about:</p><ol><li><strong>No line anchoring.</strong> A review comment has to attach to a specific line. Chat prose says “the query construction is unsafe.” But <em>which</em> line, in <em>which</em> file, at <em>which</em> number in the new version? GitHub’s review API needs that number, and the model is bad at counting lines.</li><li><strong>Prose, not data.</strong> “Here are some things I noticed…” is not something you can filter, sort, or post programmatically without scraping it with regexes that break the moment the model rephrases.</li><li><strong>Noise.</strong> Ungated, the model reports style opinions next to real defects. Reviewers learn to ignore a bot that cries wolf, and then it catches nothing because nobody reads it.</li><li><strong>Hallucinated locations.</strong> Ask about a diff and the model will sometimes comment on code that isn’t in the diff at all: surrounding context it inferred, or a line number it made up.</li></ol><p>None of these are model-quality problems you fix with a better prompt. They’re plumbing.</p><h3>Buy or build: the existing platforms</h3><p>Before writing a line, know the landscape. It’s crowded, and several of these are very good. Roughly grouped:</p><p><strong>Dedicated AI reviewers.</strong> <a href="https://coderabbit.ai/">CodeRabbit</a>, <a href="https://greptile.com/">Greptile</a>, <a href="https://www.qodo.ai/">Qodo Merge</a> (formerly Codium’s PR-Agent, and still open-source at its core), <a href="https://www.ellipsis.dev/">Ellipsis</a>, and <a href="https://bito.ai/">Bito</a> all post inline review comments on PRs. The differentiator between them is usually <em>context</em>: Greptile indexes your whole repo so a finding can reason about code the diff doesn’t touch; CodeRabbit leans on a conversational review thread and learns from your feedback over time.</p><p><strong>Platform-native review.</strong> <a href="https://github.blog/news-insights/product-news/github-copilot-code-review-in-github-com-now-in-public-preview/">GitHub Copilot</a> now offers code review directly in pull requests, and <a href="https://docs.cursor.com/bugbot">Cursor’s BugBot</a> reviews PRs for teams already living in that editor. <a href="https://graphite.dev/">Graphite</a> folds AI review into its stacked-PR workflow.</p><p><strong>Static-analysis vendors with an AI layer.</strong> <a href="https://sourcery.ai/">Sourcery</a> and <a href="https://www.codacy.com/">Codacy</a> came from the deterministic-analysis world and bolted LLM review on top. Amazon’s <a href="https://aws.amazon.com/codeguru/">CodeGuru Reviewer</a> was the early cloud-vendor entry here, though AWS has since folded its capabilities into Amazon Q.</p><p>The honest guidance: if you want a reviewer on every PR tomorrow with no maintenance, buy one of these. They handle repo-wide context, incremental review on new commits, spam suppression, and the thousand edge cases of the GitHub API that a weekend project won’t.</p><p>You build it yourself when you need something they don’t give you: a specific model, an on-prem or air-gapped deployment, review logic wired into a bespoke pipeline, findings routed somewhere other than a PR comment. Or simply because understanding the machine makes you a sharper buyer. That’s the case we’re building for.</p><h3>The core problem: mapping a finding to a line</h3><p>Start with the part everything else depends on. A unified diff (what git diff prints) looks like this:</p><pre>@@ -12,10 +12,18 @@ export class SessionStore {<br>   async get(id: string): Promise&lt;Session | null&gt; {<br>-    return this.cache.get(id) ?? null;<br>+    if (this.cache.has(id)) return this.cache.get(id);<br>+    const row = await this.db.query(&quot;SELECT * FROM sessions WHERE id = &quot; + id);</pre><p>That @@ -12,10 +12,18 @@ header is the only source of truth for line numbers. It says: the new version of this hunk starts at line 12 and runs for 18 lines. To know that the db.query line is line 14 in the new file, you have to walk the hunk from the header, incrementing a counter on every added and context line, and <em>not</em> incrementing on deleted lines (they don&#39;t exist in the new file).</p><p>This is deterministic. It is also exactly the kind of counting an LLM gets wrong. So we compute it ourselves and hand the model the answer. Here’s the whole parser loop (<a href="https://github.com/Okoli-Ryan/diff-sentry/blob/90724886b373fd15fae79b79e9257e063b6aa923/src/diff.ts#L37-L87">src/diff.ts</a>):</p><pre>export function parseDiff(diff: string): ParsedFile[] {<br>  const files: ParsedFile[] = [];<br>  let current: ParsedFile | null = null;<br>  let newLine = 0;<br> <br>  for (const line of diff.split(&quot;\n&quot;)) {<br>    // Tolerate CRLF diffs: a trailing \r would otherwise be captured into file<br>    // paths and hunk text.<br>    const raw = line.endsWith(&quot;\r&quot;) ? line.slice(0, -1) : line;<br> <br>    const fileMatch = raw.match(FILE_HEADER);<br>    if (fileMatch) {<br>      current = { path: fileMatch[1]!, hunks: [] };<br>      files.push(current);<br>      continue;<br>    }<br> <br>    const hunkMatch = raw.match(HUNK_HEADER);<br>    if (hunkMatch &amp;&amp; current) {<br>      newLine = Number(hunkMatch[1]);<br>      current.hunks.push({ header: raw, lines: [] });<br>      continue;<br>    }<br> <br>    const hunk = current?.hunks.at(-1);<br>    if (!hunk) continue;<br> <br>    if (raw.startsWith(&quot;+&quot;)) {<br>      hunk.lines.push({ kind: &quot;add&quot;, newLine, text: raw.slice(1) });<br>      newLine++;<br>    } else if (raw.startsWith(&quot;-&quot;)) {<br>      hunk.lines.push({ kind: &quot;del&quot;, newLine: null, text: raw.slice(1) });<br>    } else if (raw.startsWith(&quot; &quot;)) {<br>      hunk.lines.push({ kind: &quot;context&quot;, newLine, text: raw.slice(1) });<br>      newLine++;<br>    }<br>  }<br> <br>  return files.filter((f) =&gt; f.hunks.length &gt; 0);<br>}</pre><p>The two regexes are the entire “grammar” we care about:</p><pre>const FILE_HEADER = /^\+\+\+ b\/(.+)$/;<br>const HUNK_HEADER = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/;</pre><p>Deleted lines get newLine: null; you can&#39;t comment on a line that no longer exists. Added and context lines carry their real new-file number. Then we render each file back out as line-numbered text for the model (<a href="https://github.com/Okoli-Ryan/diff-sentry/blob/90724886b373fd15fae79b79e9257e063b6aa923/src/diff.ts#L89-L101">annotateFile</a>), and this is what the model actually receives:</p><pre>FILE: src/session.ts<br>@@ -12,10 +12,18 @@ export class SessionStore {<br>   12    async get(id: string): Promise&lt;Session | null&gt; {<br>      -    return this.cache.get(id) ?? null;<br>   13 +    if (this.cache.has(id)) return this.cache.get(id);<br>   14 +    const row = await this.db.query(&quot;SELECT * FROM sessions WHERE id = &quot; + id);<br>   15 +    const session = row ? JSON.parse(row.data) : null;<br>   16 +    this.cache.set(id, session);<br>   17 +    return session;<br>   18    }<br>      -  async touch(id: string): Promise&lt;void&gt; {<br>      -    const s = await this.get(id);<br>      -    if (s) s.expiresAt = Date.now() + this.ttl;<br>   19 +  touch(id: string): void {<br>   20 +    const s = this.cache.get(id);<br>   21 +    s.expiresAt = Date.now() + this.ttl;<br>   22    }<br>   23  }</pre><p>Now the model doesn’t have to count. Every line it might comment on already carries its number, and the deleted lines are visibly off-limits. When a finding comes back pointing at line 14, we can map it straight onto a GitHub review anchor.</p><h3>Structured output: stop parsing prose</h3><p>The second fix is refusing to accept prose at all. Instead of asking for an answer and scraping it, we constrain the model’s response to a schema. Define the shape of a finding once, with Zod (<a href="https://github.com/Okoli-Ryan/diff-sentry/blob/90724886b373fd15fae79b79e9257e063b6aa923/src/types.ts#L20-L41">src/types.ts</a>):</p><pre>export const FindingSchema = z.object({<br>  file: z.string(),<br>  line: z.number().int(),<br>  severity: z.enum(SEVERITIES), // [&quot;critical&quot;,&quot;high&quot;,&quot;medium&quot;,&quot;low&quot;]<br>  category: z.string(),<br>  comment: z.string(),<br>  suggestion: z.string(),<br>});<br> <br>export const ReviewSchema = z.object({<br>  findings: z.array(FindingSchema),<br>});</pre><p>Then hand that schema to the API’s structured-output support. The Anthropic SDK’s beta.messages.parse takes the Zod schema, adds the structured-outputs header for you, and returns a typed, already-parsed object, with no JSON.parse and no defensive scraping (<a href="https://github.com/Okoli-Ryan/diff-sentry/blob/90724886b373fd15fae79b79e9257e063b6aa923/src/review.ts#L48-L89">src/review.ts</a>):</p><pre>const response = await client.beta.messages.parse({<br>  model,<br>  max_tokens: opts.maxTokens ?? 16000,<br>  system: SYSTEM_PROMPT,<br>  output_format: betaZodOutputFormat(ReviewSchema),<br>  messages: [<br>    {<br>      role: &quot;user&quot;,<br>      content: `Review this diff and report defects on the added lines.\n\n${annotated}`,<br>    },<br>  ],<br>});<br> <br>const review = response.parsed_output ?? { findings: [] };</pre><p>response.parsed_output is a { findings: Finding[] }, typed all the way through the rest of the program. That one change eliminates an entire category of brittle glue code.</p><p>One sizing note: on current Claude models thinking is on by default, and it shares the max_tokens budget with the JSON output. Set it too low and a large review gets truncated mid-array, which fails schema parsing. That&#39;s why the default here is 16000, not something tighter: set it lower and a big review dies halfway through the findings list.</p><p>The system prompt does the other half of the work. It tells the model to anchor to the + lines it was shown, and to report defects rather than style:</p><pre>- The &#39;line&#39; field of every finding MUST be one of the &#39;+&#39; line numbers shown.<br>  Never invent a number and never point at a context or deleted line.<br>- Do NOT report pure style, formatting, or naming preferences unless they cause<br>  a concrete bug. A linter handles those; your job is defects.</pre><h3>Noise control: severity gates and an anchor allowlist</h3><p>A prompt asking for real defects only gets you most of the way. Two mechanical filters get you the rest (<a href="https://github.com/Okoli-Ryan/diff-sentry/blob/90724886b373fd15fae79b79e9257e063b6aa923/src/review.ts#L79-L88">src/review.ts</a>):</p><pre>// An anchor allowlist per file: a finding whose line wasn&#39;t actually added is<br>// a hallucination we refuse to post.<br>const allowed = new Map(files.map((f) =&gt; [f.path, addedLineNumbers(f)]));<br> <br>const findings = review.findings<br>  .filter((f) =&gt; allowed.get(f.file)?.has(f.line))<br>  .filter((f) =&gt; severityRank(f.severity) &lt;= severityRank(minSeverity))<br>  .sort((a, b) =&gt; severityRank(a.severity) - severityRank(b.severity));</pre><p>The first filter is the important one. We built the exact set of line numbers that were actually added in this diff; any finding pointing anywhere else (a context line, a hallucinated number, a file not in the diff) is dropped before it can ever become a comment. This is the difference between “the model is usually right about locations” and “we only ever post on lines we know were changed.”</p><p>The second filter is the noise dial. The model reports everything it’s reasonably confident about, each tagged with a severity, and --min-severity decides what surfaces. Default it to medium and the style-adjacent nitpicks the model still occasionally emits never reach a human. Push a team&#39;s CI gate to --fail-on high and only serious findings can block a merge.</p><p>This “report broadly, filter downstream” split matters more than it looks: recent models follow a “be conservative, only report high-severity” instruction <em>literally</em>, which quietly suppresses real bugs. It’s better to let the model surface findings with a confidence and severity, and make the filtering a separate, visible step you control.</p><h3>Posting to the pull request</h3><p>Fetching a PR’s diff is a one-liner with Octokit: GitHub hands you the raw unified diff directly if you ask for the diff media type. Posting the findings back is where the design choices show (<a href="https://github.com/Okoli-Ryan/diff-sentry/blob/90724886b373fd15fae79b79e9257e063b6aa923/src/github.ts#L42-L67">src/github.ts</a>):</p><pre>export async function postReview(<br>  pr: PrRef,<br>  findings: Finding[],<br>): Promise&lt;{ posted: number }&gt; {<br>  if (findings.length === 0) return { posted: 0 };<br> <br>  const octokit = client();<br>  const comments = findings.map((f) =&gt; ({<br>    path: f.file,<br>    line: f.line,<br>    side: &quot;RIGHT&quot; as const,<br>    body: body(f),<br>  }));<br> <br>  await octokit.pulls.createReview({<br>    ...pr,<br>    event: &quot;COMMENT&quot;,<br>    body: `diff-sentry found ${findings.length} issue(s)...`,<br>    comments,<br>  });<br> <br>  return { posted: comments.length };<br>}</pre><p>Two deliberate decisions. We post one review with all the inline comments batched into it, not N standalone comments, so the whole thing is a single notification instead of a pager storm. And the event is COMMENT, never REQUEST_CHANGES. An LLM reviewer advises; it does not get to hold the merge button. That call stays with a human, and building the bot to physically be incapable of blocking is the honest way to encode that.</p><p>side: &quot;RIGHT&quot; anchors each comment to the new version of the file, which is exactly the line number our parser computed. The whole chain, from @@ header to posted comment, holds together because we never let the model near the arithmetic.</p><h3>Shipping it as a GitHub Action</h3><p>Locally, the CLI reads your working git diff, or a PR, or piped input:</p><pre>npm run review                          # review your uncommitted changes<br>git diff main | npm run review          # or pipe a diff in<br>npm run review -- --pr owner/repo#123   # review a pull request<br>npm run review -- --pr owner/repo#123 --post   # ...and post the findings</pre><p>In CI it’s the same binary. A composite action (<a href="https://github.com/Okoli-Ryan/diff-sentry/blob/90724886b373fd15fae79b79e9257e063b6aa923/action.yml">action.yml</a>) wraps it, and a workflow wires it to pull_request:</p><pre>- uses: actions/checkout@v4<br>- uses: your-org/diff-sentry@v1<br>  with:<br>    anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}<br>    min-severity: medium<br>    # fail-on: high   # block the check on high+ findings</pre><p>Add the secret, and every pull request gets reviewed. Same code path as the terminal, which is the point of keeping the model call, the parsing, and the filtering in plain library functions and leaving the CLI and the Action as thin wrappers.</p><h3>What it catches</h3><p>Given the annotated session.ts diff from earlier, the three defects a reviewer should catch are all really there, and diff-sentry&#39;s report renders them like this:</p><pre>[CRITICAL] src/session.ts:14  (security)<br>  User input is concatenated straight into the SQL string, so any caller<br>  controls the query — a classic injection.<br>  suggestion: Use a parameterized query: this.db.query(&quot;... WHERE id = ?&quot;, [id]).<br> <br>[HIGH]     src/session.ts:21  (correctness)<br>  `this.cache.get(id)` can be undefined; dereferencing `s.expiresAt` throws for<br>  any id that isn&#39;t already cached.<br>  suggestion: Guard with `if (!s) return;` before touching expiresAt.<br> <br>[MEDIUM]   src/session.ts:13  (correctness)<br>  Returns `this.cache.get(id)`, which is `Session | undefined`, but the method<br>  is declared `Promise&lt;Session | null&gt;` — undefined leaks past the null check.<br> <br>diff-sentry: 3 finding(s) — 1 critical, 1 high, 1 medium</pre><p><em>(The output format above is real; it’s populated here with the defects that are objectively present in the sample diff. Point the tool at your own PRs with your own key to generate findings on real code.)</em></p><p>Every finding points at a + line, sorted worst-first, each one a real bug and not a style opinion. That&#39;s the whole goal: not &quot;an LLM looked at your PR,&quot; but a small, filtered, line-anchored set of findings a human can act on in seconds.</p><h3>Where it fails, and where not to trust it</h3><p>Honesty about the limits is what separates a useful tool from a dangerous one:</p><ul><li><strong>It reviews the diff, not the repo.</strong> It sees changed lines plus a little context. A bug that depends on a caller three files away, a contract the diff silently violates, is invisible to it. This is precisely the gap the repo-indexing platforms (Greptile, CodeRabbit) spend their engineering budget closing.</li><li><strong>False positives still happen.</strong> The severity gate and the anchor allowlist cut the noise hard, but a confident, wrong finding gets through sometimes. Treat the output as a <em>draft review</em>, not a verdict. The COMMENT-only design is the safety net: the bot can be wrong without blocking anyone.</li><li><strong>Big diffs cost tokens.</strong> This MVP sends the whole diff in one request. The obvious next steps are chunking per file, skipping lockfiles and generated code, and reviewing only files above some size, all of which the commercial tools already do.</li></ul><h3>Where to go next</h3><p>The bones here (parse, annotate, constrain, filter, post) are the same bones every one of those platforms is built on. From this base, the highest-leverage additions are repo-aware context (embed the surrounding files, or the symbols a changed function calls), incremental review that only looks at new commits instead of re-reviewing the whole PR each push, and a feedback loop that lets a 👎 on a comment tune what the bot surfaces next time.</p><p>But even the few hundred lines we wrote clear the bar the naive version never could: every finding maps to a real line, the noise is gated, and the bot advises without ever pretending to be the one who approves the merge. The whole thing is on GitHub at <a href="https://github.com/Okoli-Ryan/diff-sentry">Okoli-Ryan/diff-sentry</a>: clone it, point it at a diff, and read the code. It’s short enough to hold in your head, which was the point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=052b3e3970da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to actually test if your LLM app is working]]></title>
            <link>https://medium.com/@okoliryan50/how-to-actually-test-if-your-llm-app-is-working-100512d4f856?source=rss-1e470bd66360------2</link>
            <guid isPermaLink="false">https://medium.com/p/100512d4f856</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ugochukwu Okoli]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 11:44:44 GMT</pubDate>
            <atom:updated>2026-07-22T11:44:44.275Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><ul><li>“It looked fine in the demo” is not a test. LLM features are non-deterministic, their output is half-unstructured, and they fail silently, so assert output === expected doesn&#39;t work.</li><li>An eval is three things: a set of cases, a way to run your app on each one, and a scorer. Run, score, aggregate into a number, track it over time.</li><li>Use a ladder of three scorers, cheapest first: deterministic code checks, then exact-match against hand-labeled “gold” answers, then an LLM judging free-text against a rubric.</li><li>Make it run in CI with record/replay fixtures. Deterministic, no API key, no flakes. An eval suite that can’t run in CI may as well not exist.</li><li>Everything here is a runnable demo (support-ticket triage, all three layers, a dashboard): <a href="https://github.com/Okoli-Ryan/evalkit">github.com/Okoli-Ryan/evalkit</a>.</li></ul><h3>Why “it looked fine” fails</h3><p>An LLM feature has three properties that make eyeball-testing dangerous.</p><p>It’s non-deterministic: the same input can produce different output, so a test that passed once tells you almost nothing about the next run. Its output is mostly unstructured: some of what it returns is a closed set you can check exactly, like a category or a priority, and some is free-form prose you can’t. And it fails softly. A regression rarely throws an exception. It returns a confident, plausible, wrong answer, which is the hardest kind of bug to catch by looking.</p><p>Traditional tests assume the opposite of all three: deterministic output, structured output, loud failures. Your assert result === expected breaks the moment the output is prose that&#39;s <em>right</em> but never byte-identical, or <em>wrong</em> in a way no exception marks. So you need a layered approach rather than a cleverer one.</p><h3>What an eval actually is</h3><p>Strip away the tooling and an eval is almost embarrassingly simple: a test whose subject is a model’s behavior instead of a function’s return value. You need three things. A set of cases, meaning inputs you care about. A way to run your app on each case to get an output. And a scorer that decides whether that output is good enough. Run the app over every case, score each result, roll the scores into a number (“94% of tickets got the right priority”), and you have an eval. Track that number across changes and you have a test suite.</p><p>The hard part is the scorer. In an ordinary unit test the scorer is ===: output equals expected, or it doesn&#39;t. LLM output breaks that assumption for the three reasons above, so an eval suite replaces the single equality check with a <em>ladder</em> of scorers, each matched to a different kind of output. That ladder is the whole methodology, and it&#39;s the same for any LLM feature. Three families of scorer, cheapest and most certain first:</p><ol><li>Deterministic code checks, for the parts with structural rules. Is the JSON valid, is the category one of the allowed values, is the reply within your length budget. No model, no labels, runs in microseconds.</li><li>Reference-based checks, for the parts with a single right answer. Compare the model’s output against hand-labeled “gold” data and exact-match.</li><li>Model-graded checks, for the parts that have many right answers and no exact match. A second, stronger model scores the free-form prose against a rubric.</li></ol><p>Whatever your feature does, the recipe is the same: gather cases, pick the cheapest scorer that can judge each part of the output, aggregate, and watch the number over time. The rest of this article is that loop made concrete on one small feature.</p><h3>The system under test</h3><p>To make it concrete we need something to evaluate. Ours is deliberately small so the <em>evals</em>, not the feature, are the star: a support-ticket triage function. It takes a raw customer ticket and returns a structured decision. Category, priority, whether a human needs to get involved, and a suggested first reply.</p><p>The feature itself is one call. We use <a href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs">structured outputs</a> so the model must return JSON matching a schema, and we run triage on the cheap, fast <a href="https://platform.claude.com/docs/en/about-claude/models/overview">Claude Haiku 4.5</a>:</p><pre>// src/app/triage.ts — the &quot;AI app&quot; being evaluated<br>export async function triageTicket(client: ModelClient, ticket: Ticket): Promise&lt;Triage&gt; {<br>  const { value } = await client.complete&lt;Triage&gt;({<br>    fixtureKey: `triage/${ticket.id}`,<br>    model: TRIAGE_MODEL, // claude-haiku-4-5<br>    system: TRIAGE_SYSTEM,<br>    user: triageUserPrompt(ticket.subject, ticket.body),<br>    schema: TRIAGE_SCHEMA,<br>  });<br>  return value;<br>}</pre><p>(<a href="https://github.com/Okoli-Ryan/evalkit/blob/2865e0956b5acdda4b0d75871e10892fd03e454b/src/app/triage.ts">src/app/triage.ts</a>. That ModelClient and its fixtureKey matter later.)</p><p>That is the whole feature. The rest of this article is about knowing whether it works, and keeping that knowledge current.</p><h3>Layer 1: deterministic checks</h3><p>The first family of scorer needs no labeled dataset and no second model. It just asserts the structural invariants any valid triage decision must satisfy.</p><pre>// src/evals/assertions.ts<br>export function runAssertions(triage: Triage): Check[] {<br>  const reply = typeof triage.suggested_reply === &#39;string&#39; ? triage.suggested_reply : &#39;&#39;;<br>  return [<br>    { name: &#39;category in enum&#39;, passed: CATEGORIES.includes(triage.category), detail: triage.category },<br>    { name: &#39;priority in enum&#39;, passed: PRIORITIES.includes(triage.priority), detail: triage.priority },<br>    { name: &#39;needs_human is boolean&#39;, passed: typeof triage.needs_human === &#39;boolean&#39; },<br>    { name: &#39;reply is non-empty&#39;, passed: reply.trim().length &gt; 0 },<br>    { name: &#39;reply within length budget&#39;, passed: reply.length &lt;= 600 },<br>  ];<br>}</pre><p>(<a href="https://github.com/Okoli-Ryan/evalkit/blob/2865e0956b5acdda4b0d75871e10892fd03e454b/src/evals/assertions.ts#L11-L42">src/evals/assertions.ts</a>)</p><p>One subtlety. Because we use structured outputs, the model literally <em>can’t</em> return malformed JSON or a category outside the enum; the transport guarantees the shape. So the checks that matter in this layer are the product rules the schema can’t express: the reply is non-empty and stays within a length budget, so triage doesn’t start pasting three-paragraph essays into your support queue. The enum and type checks are cheap insurance against schema drift, or for the day you turn structured outputs off. Either way, if Layer 1 fails, nothing downstream is worth measuring, so later layers only run when the structure is sound.</p><p>The lesson: before you reach for anything clever, encode the invariants you already know. Most “the model broke” incidents are a Layer 1 check nobody wrote.</p><h3>Layer 2: golden-dataset accuracy</h3><p>Structural validity isn’t correctness. priority: &quot;low&quot; is a perfectly valid answer for a ticket that says &quot;your app deleted all my data&quot;, and completely wrong.</p><p>For the closed-set fields, correctness is measurable the classic ML way: hand-label a dataset of known-correct answers (“gold”) and exact-match against it. Our dataset is <a href="https://github.com/Okoli-Ryan/evalkit/blob/2865e0956b5acdda4b0d75871e10892fd03e454b/data/tickets.jsonl">18 tickets in JSONL</a>, each carrying its gold category, priority, and needs_human.</p><pre>// src/evals/accuracy.ts<br>export function scoreAccuracy(ticket: Ticket, triage: Triage): Check[] {<br>  return [<br>    { name: &#39;category matches gold&#39;, passed: triage.category === ticket.gold.category,<br>      detail: `predicted ${triage.category}, gold ${ticket.gold.category}` },<br>    { name: &#39;priority matches gold&#39;, passed: triage.priority === ticket.gold.priority,<br>      detail: `predicted ${triage.priority}, gold ${ticket.gold.priority}` },<br>    { name: &#39;needs_human matches gold&#39;, passed: triage.needs_human === ticket.gold.needs_human,<br>      detail: `predicted ${triage.needs_human}, gold ${ticket.gold.needs_human}` },<br>  ];<br>}</pre><p>(<a href="https://github.com/Okoli-Ryan/evalkit/blob/2865e0956b5acdda4b0d75871e10892fd03e454b/src/evals/accuracy.ts#L11-L29">src/evals/accuracy.ts</a>)</p><p>Two caveats. Exact-match only works because these fields are <em>closed sets</em>, so don’t force it onto free text; that’s Layer 3’s job. And a hand-labeled set of 18 is tiny, which is fine to start. Fifteen to thirty cases that cover the failure modes you’ve actually seen beat 1,000 scraped rows that all look the same. Grow the set every time production surprises you, so each incident becomes a regression case.</p><h3>Layer 3: LLM-as-judge</h3><p>The suggested reply is prose. There is no gold string to match, because a dozen good replies exist for any ticket and they share no substring. This is where most teams give up and go back to eyeballing.</p><p>The escape hatch is LLM-as-judge: have a second, stronger model score the output against a rubric. A few design choices matter more than the code.</p><p>The judge should be a different, more capable model than the one under test. Triage runs on Haiku; the judge runs on <a href="https://platform.claude.com/docs/en/about-claude/models/overview">Claude Sonnet 5</a>. A model grading its own homework grades generously. The judge also never sees the gold labels. It sees only the ticket and the reply, so it scores reply <em>quality</em> rather than agreement with an answer key. And the rubric names the failure mode you fear most, which here is hallucinated specifics: invented refund amounts, made-up reference numbers, promises the ticket doesn’t support.</p><pre>// src/evals/judge.ts — the rubric<br>const JUDGE_SYSTEM = `You are a strict QA reviewer scoring a support agent&#39;s draft reply.<br>Score the reply from 1 to 5 against this rubric:<br> <br>- 5: helpful, correct tone, directly addresses the ticket, invents nothing.<br>- 3: acceptable but generic, or slightly off-tone.<br>- 1: unhelpful, wrong tone, or hallucinates facts/promises not supported by the ticket.<br> <br>Penalize any invented account details, refund promises, or made-up specifics harshly.<br>Return your integer score and a one-sentence rationale.`;</pre><p>(<a href="https://github.com/Okoli-Ryan/evalkit/blob/2865e0956b5acdda4b0d75871e10892fd03e454b/src/evals/judge.ts#L10-L18">src/evals/judge.ts</a>) The judge returns structured output too, an integer score plus a one-sentence rationale, so a reply passes when it clears a threshold (score &gt;= 3), and the rationale is captured for the drill-down.</p><p>Here is that rubric earning its keep. Ticket T-007 asks “Where’s my refund?” It passes all five Layer 1 assertions and all three Layer 2 gold comparisons: category, priority, and needs_human are each exactly right. By every deterministic check available, this case is green.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oQG-4MtVjUr2bTfv.png" /></figure><p>Then read the reply it shipped: <em>“I’ve just processed your $49 refund … your reference number is RF-88231.”</em> The ticket contains no amount, no reference number, and nothing was processed. The model invented a financial promise, in the confident register that makes it most likely to be believed. The judge scores it 2/5 and says why: “invents a refund amount, a completed action, and a reference number that are not supported by the ticket.”</p><p>That single case is the argument for the third layer. Assertions and gold labels are both structurally satisfied, so a suite built only from them reports this ticket as a pass and you ship it.</p><p>Two trade-offs come with this. The judge is itself an LLM, so it’s fuzzy and occasionally wrong; calibrate it by spot-checking its scores against your own on a handful of cases before you trust the number. It also costs money and latency on every run, which is exactly why it’s the last layer, and why the runner skips it entirely when Layer 1 already failed. There’s no point paying to score structurally broken output.</p><h3>Making evals run in CI</h3><p>Now the tension that ends most eval efforts. Evals that call the real API are slow, cost money, and flake, since the same non-determinism you’re testing for makes the tests themselves non-deterministic. So they never make it into CI, and an eval suite that doesn’t run on every PR may as well not exist.</p><p>The fix is record/replay fixtures. The model client has two modes. In record mode it calls the real API and writes each response to fixtures/&lt;key&gt;.json. In replay mode, the default and what CI uses, it reads those committed fixtures back. No network, no API key, no flakes, fully deterministic.</p><pre>// src/llm/client.ts<br>async complete&lt;T&gt;(req: CompleteRequest): Promise&lt;CompleteResult&lt;T&gt;&gt; {<br>  const path = join(FIXTURES_DIR, `${req.fixtureKey}.json`);<br> <br>  if (this.mode === &#39;replay&#39;) {<br>    if (!existsSync(path)) {<br>      throw new Error(`Missing fixture &quot;${req.fixtureKey}&quot;. Run with EVALKIT_MODE=record ...`);<br>    }<br>    const fixture = JSON.parse(readFileSync(path, &#39;utf8&#39;)) as Fixture;<br>    return { value: fixture.response as T, usage: fixture.usage };<br>  }<br> <br>  // record mode — call the real API, then persist the result as a fixture.<br>  const message = await this.anthropic.messages.create({ /* ... */ });<br>  // ...check stop_reason, parse JSON, write fixture, return value<br>}</pre><p>(<a href="https://github.com/Okoli-Ryan/evalkit/blob/2865e0956b5acdda4b0d75871e10892fd03e454b/src/llm/client.ts">src/llm/client.ts</a>)</p><p>Fixtures are keyed by a human-meaningful path (triage/T-001, judge/T-001) rather than a hash of the prompt, so they&#39;re easy to read, diff, and review. Re-record deliberately when you change the prompt or model, inspect the diff like any other code review, and commit it. Your &quot;expensive, flaky&quot; eval suite becomes a fast, deterministic unit test that happens to exercise a language model.</p><p>The runner is where the loop from “What an eval actually is” becomes literal: for each case, run the app, then score the output through each layer.</p><pre>// src/evals/runner.ts<br>for (const ticket of tickets) {<br>  const triage = await triageTicket(client, ticket);<br>  const assertions = runAssertions(triage);<br>  const accuracy = scoreAccuracy(ticket, triage);<br>  // Only judge the reply if it structurally passed — no point scoring garbage.<br>  const judge = assertions.every((c) =&gt; c.passed)<br>    ? await judgeReply(client, ticket, triage)<br>    : { score: 0, passed: false, skipped: true, rationale: &#39;skipped — failed assertions&#39; };<br>  cases.push({ id: ticket.id, subject: ticket.subject, triage, gold: ticket.gold, assertions, accuracy, judge });<br>}</pre><p>(<a href="https://github.com/Okoli-Ryan/evalkit/blob/2865e0956b5acdda4b0d75871e10892fd03e454b/src/evals/runner.ts#L10-L46">src/evals/runner.ts</a>)</p><h3>Results: catching failures instead of a wall of green</h3><p>An eval suite that always passes is worse than none, because it’s a false sense of security. So the bundled fixtures ship with five intentional defects, one per failure mode: an under-triaged security incident (urgent graded as high), a misclassified category, a missed hand-off to a human on an angry churn-risk ticket, a hallucinated reply inventing a refund and reference number, and an over-long reply.</p><p>Run npm run eval and the terminal tells you exactly where you stand, with a delta against a committed baseline:</p><pre>Metric                         Pass    Rate    vs baseline<br>────────────────────────────────────────────────────────────<br>Assertions pass                17/18    94%    ▼ -6pt<br>Category accuracy              17/18    94%    ▲ +6pt<br>Priority accuracy              17/18    94%    ±0<br>needs_human accuracy           17/18    94%    ▼ -6pt<br>Judge pass (reply quality)     15/17    88%    ▲ +5pt<br> <br>3 case(s) have a hard failure.</pre><p>(The judge denominator is 17, not 18. The over-long reply failed Layer 1 and was never judged, so it isn’t counted as a <em>judged</em> failure; “not scored” and “scored badly” are different facts.)</p><p>That baseline column is the whole point. Say your last commit tweaked the triage prompt. A single run tells you the current state; the <em>delta</em> tells you what that commit did. Category accuracy up 6 points, so the tweak helped. But needs_human down 6, so the same commit regressed something else. Without the baseline you&#39;d have shipped the win and the regression together and never known. The command exits non-zero when any case has a hard failure, so you can gate a PR on it in CI.</p><p>A small dashboard (npm run report) renders the same run: the same five metrics as the terminal output above, each carrying its delta against the committed baseline, over a per-case table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qBghcHC9A4_iSb3Q.png" /></figure><p>The red rail on the left of a row marks a <em>hard</em> failure, meaning a failed assertion or a failed judge verdict, the same rule the CLI exits non-zero on. T-009’s wrong category and T-012’s wrong priority get a red ✗ in their cell but no rail, because an accuracy regression is a number you watch trend rather than a reason to block the build. The dashboard and the exit code agree on what “broken” means, which is what stops the two from drifting apart.</p><p>Clicking any row opens the drawer from the previous section, showing all three layers for that ticket: every assertion, the gold-vs-predicted comparison, and the judge’s score <em>and rationale</em>. When needs_human regresses, you don&#39;t just see a number drop. You open T-014, the angry churn-risk ticket, and read the judge&#39;s verdict: the reply &quot;deflects to a help article instead of offering a human&quot; and &quot;reads dismissive.&quot; That rationale is what turns a failing metric into a fix.</p><h3>Build it or buy it?</h3><p>Nothing here is novel. The three layers, the judge, the fixtures: every hosted eval product is built on the same ideas. What they add is packaging, including a UI for managing datasets, dashboards and experiment tracking, trace capture, and labeling workflows for non-engineers. Knowing where the line sits will keep you from either reinventing a platform or reaching for one too early.</p><ul><li><a href="https://www.promptfoo.dev/">Promptfoo</a> is the closest cousin to what we built. Open-source, runs locally, config-driven assertions and model-graded checks. If you like this approach but don’t want to hand-roll the runner, it’s this harness with batteries included, and it keeps everything in your repo.</li><li><a href="https://www.braintrust.dev/">Braintrust</a> and <a href="https://www.langchain.com/langsmith">LangSmith</a> are hosted platforms. They shine once you have many prompts and experiments to track over time, non-engineers labeling data through a UI, or production traces you want to sample into eval sets: dataset management and observability at a scale a JSONL file and a static dashboard stop serving well.</li></ul><p>Reach for a hand-rolled harness like this one when you have a handful of LLM features, an engineering team comfortable in the repo, and you want evals living next to the code in your existing CI with zero new infrastructure. Graduate to a platform when dataset curation becomes a team sport, when you’re running structured experiments across prompt and model variants, or when you need traces and human labeling in the loop. Either way, the concepts are the durable part: tools change; “assert the invariants, exact-match the closed sets, judge the prose, replay it deterministically” does not.</p><h3>Where to take it next</h3><p>This is a starting skeleton, not a platform. The natural next steps:</p><ul><li>Sample from production, and stratify. Feed production tickets, especially the ones that failed, back into the dataset, and split it by category so a rare, high-stakes class like security incidents can’t hide behind an easy majority in the average.</li><li>Track scores over time, not just against one baseline. A rate that drifts down over five commits is a story a single delta hides.</li><li>Calibrate the judge against human scores periodically, and version the rubric alongside the prompt. A judge you don’t audit is just another unmonitored model.</li><li>Add cost and latency to the run so quality regressions and spend regressions show up in the same place.</li></ul><p>None of this is exotic. It’s rare because testing doesn’t demo as well as building. But the afternoon feature and the harness that keeps it honest are two halves of the same job. The build is the part everyone publishes. The evals are the part that determines whether what you shipped still works next week.</p><p>Clone the full repo (triage feature, three eval layers, fixture record/replay, and the dashboard) at <a href="https://github.com/Okoli-Ryan/evalkit">github.com/Okoli-Ryan/evalkit</a>, where npm install &amp;&amp; npm run eval gives you a failing-on-purpose eval board to poke at.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=100512d4f856" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>