<?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 Burak Hamuryen on Medium]]></title>
        <description><![CDATA[Stories by Burak Hamuryen on Medium]]></description>
        <link>https://medium.com/@hamuryen?source=rss-5d1e33604f80------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Burak Hamuryen on Medium</title>
            <link>https://medium.com/@hamuryen?source=rss-5d1e33604f80------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:43:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamuryen/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[Your Kafka Consumers Are Becoming a Workflow Engine]]></title>
            <link>https://medium.com/@hamuryen/your-kafka-consumers-are-becoming-a-workflow-engine-6e7f424baa3c?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e7f424baa3c</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 08:01:04 GMT</pubDate>
            <atom:updated>2026-10-14T08:01:04.367Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Retries are the easy part. Try cancelling work that has already started.</em></p><figure><img alt="Video job cards move through a branching mechanical workflow; an orange gate stops one branch while another continues toward completion." src="https://cdn-images-1.medium.com/max/1024/1*iMvG3_IWlIbPqQEzvJBSKQ.png" /><figcaption>Once a job can branch, wait and be cancelled, its state needs an owner beyond the next message.</figcaption></figure><p>A user requests a video export, waits a few minutes, then clicks Cancel. The UI confirms it. Twenty minutes later, an email arrives: your export is ready.</p><p>Every message may have been delivered correctly. The renderer finished its job. The notification consumer handled the completion event. The cancellation consumer updated its own record. The system still did something the user had asked it to stop doing.</p><p>This is a hypothetical example, drawn from the kinds of backend and video systems I work on. It is a useful way to examine a design that often starts innocently: a few Kafka consumers, each responsible for one step, connected by topics. As requirements accumulate, the consumers acquire timers, retry rules, cancellation flags, and recovery scripts. Eventually, someone has to explain what the whole operation is doing.</p><p>A recent <a href="https://www.reddit.com/r/apachekafka/comments/1w6gv9m/we_used_kafka_as_workflow_execution_engine/">discussion about using Kafka as a workflow execution engine</a> raised this same boundary. Kafka can remain a good part of the architecture. The question is where the application stores the decisions that must survive a worker dying halfway through the job.</p><h3>Start with the promise behind Cancel</h3><p>Consider an export that waits for a recording interval, renders a clip, stores the result, and notifies the requester. Some jobs finish quickly. Others wait for a camera to reconnect or compete for a limited pool of render workers.</p><p>What does cancellation promise?</p><p>It might mean stop scheduling new work and hide any later result. It might mean request that the renderer stop, accepting that an already running operation can finish. It probably cannot mean recall an email that has already been accepted by a mail service.</p><p>These are different contracts. Pick one before adding a cancelled flag.</p><p>For this example, use a modest contract: cancellation prevents new steps from being authorized after it is committed. Already authorized external operations may finish. Their results are recorded, but they cannot advance the cancelled export. The UI reports cancellation requested while external work is still draining.</p><p>That contract needs a shared decision point. A notification consumer reading a stale copy of cancelled = false cannot enforce it on its own.</p><p>One implementation is a transaction on the export record: check the current state and version, authorize the next step, and record its dispatch intent together. Cancellation uses the same concurrency control. Whichever transaction commits first determines whether the step was authorized. A dispatch worker can still check for cancellation before sending, but that extra check cannot make a remote call atomic with the database.</p><p>The race has a defined outcome now. It has not disappeared.</p><p>Applied to the opening failure, this contract changes the outcome: cancellation commits before rendering finishes, so the completion handler never authorizes the email. The render may still produce an artifact; the UI shows cancellation requested until outstanding work is reconciled.</p><p>If the renderer supports cancellation, record a durable cancel intent and deliver it using the known operation key or job ID. Retry an uncertain response and reconcile the renderer’s eventual status. A database flag alone will not release its GPU. If cancellation is unsupported or arrives too late, suppress further steps and clean up the unused artifact after determining that no active worker still needs it.</p><h3>An offset cannot answer the customer’s question</h3><p>Suppose the export request was consumed at partition 7, offset 812. Later messages say the recording became available and rendering started. Those positions help track delivery. They do not directly tell support whether export exp-42 is waiting, stuck, cancelled, or safe to retry.</p><p>The application needs a current view with enough information to make its next decision. For this example, I would expect something like:</p><pre>export_id           exp-42<br>state               rendering<br>state_version       9<br>workflow_version    2<br>cancelled_at        null<br>deadline            2026-10-16T18:00:00Z<br>render_operation    exp-42/render/&lt;input-digest&gt;<br>renderer_job_id     job-781<br>next_attempt_at     null<br>last_error          null</pre><p>The input digest identifies an immutable specification: source recording version, interval, and render settings. The workflow version identifies the behavior governing this export. The state version supports concurrency checks. They serve different purposes; using one counter for all three makes recovery harder to reason about.</p><p>This view can live in a database or be maintained through stream processing. <a href="https://kafka.apache.org/41/streams/core-concepts/">Kafka Streams supports stateful processing and exactly-once processing guarantees</a> when configured appropriately. It would be misleading to describe Kafka as incapable of maintaining application state.</p><p>The design question is who owns that state, how it is restored, and which operations are atomic with it. Reconstructing a history from events can be valid. It still requires decisions about event retention, schema evolution, and how old events map to today’s code.</p><h3>The lost response is where retries become business logic</h3><p>The render consumer sends a request. The renderer accepts it and creates job-781. Before the response reaches the consumer, the connection fails.</p><p>The consumer sees a timeout. The renderer sees a running job. Retrying with a new operation ID can start a second render. I covered the general lost-response problem in <a href="https://medium.com/@hamuryen/ai-agents-are-distributed-systems-treat-them-like-one-c4fcd0455708">AI Agents Are Distributed Systems</a>. Here the additional requirement is preserving one step’s identity across the lifetime of an export, including cancellation and later recovery.</p><p>Kafka’s <a href="https://kafka.apache.org/41/design/design/">delivery semantics and transaction model</a> describe the guarantees available inside its processing boundary. A Kafka transaction does not automatically include a remote renderer or an email provider. Exactly-once processing within Kafka is valuable; the external effect still needs its own agreement.</p><p>First, the export request itself needs a client-supplied idempotency key, scoped to its customer, so resubmitting the same request returns the same export ID. Reject conflicting input for that key. Then define each step’s operation identity before dispatch:</p><pre>operation_key = export_id + step_name + digest(immutable_step_input)</pre><p>Retries of the same logical step reuse this key. A deliberate new export receives a new export ID. A changed render specification needs a new logical operation, not silent reuse of the old key.</p><p>The renderer must atomically associate that key with one job and return the existing job for repeated requests. It must also reject the same key with conflicting input. A client-side lookup followed by an ordinary create call is insufficient: two callers can both observe no job and both create one.</p><p>Key retention matters too. If the renderer forgets its deduplication record after an hour while consumers can replay a week-old request, the supposed guarantee ends after an hour. Keep the identity for the retry and recovery horizon, or reject operations whose safe retry window has expired.</p><p>Without cooperation from the renderer, an ambiguous timeout may need reconciliation or operator intervention. Changing the message broker cannot tell you whether that external operation happened.</p><h3>A database state machine is a serious middle option</h3><p>Before adding a workflow platform, I would examine whether a small explicit state machine is enough.</p><p>For each incoming event, a database transaction can record the event ID in an inbox, validate the transition, update the export, and insert any outgoing intent into an outbox. A unique inbox key prevents the same delivered event from applying the transition twice. Commit the Kafka offset only after that durable handoff.</p><p>If the database commits and the offset commit fails, redelivery finds the inbox entry and does no additional work. If processing is concurrent, commit only the contiguous completed range for each partition; acknowledging a later record must not skip an earlier unfinished one.</p><p>An outbox relay publishes the recorded intent. It can publish twice if it crashes between publishing and recording progress, so recipients still deduplicate. Debezium’s <a href="https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html">outbox event router</a> documents one way to represent and route these records, including event identity and aggregate keys. The pattern closes the database-update/publication gap; it does not make every downstream effect unique.</p><p>Once accepted, work belongs to the durable job record. Do not keep the consumer waiting for a two-hour render to finish. A separate worker dispatches it, records the remote job identity, and reconciles completion. An expired worker lease can permit takeover, but does not prove the old worker stopped. Version checks and the external operation key still matter.</p><p>For database updates, make the check and update atomic: accept a transition only if the stored state version still matches the worker’s expected version, then increment it. Fencing stale external writes requires the external service to enforce a monotonically increasing token as well. An idempotency key deduplicates the same operation; it does not by itself reject every command from a superseded worker.</p><p>Within one topic, a stable partitioning scheme can keep an export’s records in the same partition and therefore in log order. Records in different topics have no shared Kafka ordering guarantee, even when they use the same export ID as their key. Neither arrangement makes asynchronously executed work finish in order. Conversely, one slow render only blocks unrelated records if the processing design waits synchronously or otherwise serializes them behind it. Kafka is not forcing that choice.</p><p>The workflow code now has explicit answers for failure cases:</p><figure><img alt="Six failure cases and decisions: deduplicate requests; reconcile timed-out dispatch; record late completion without notification; match old results to operation identity; persist expired deadlines; recover expired leases while preserving step identity." src="https://cdn-images-1.medium.com/max/1024/1*emB4Kbm5f5I89-gu37cUdw.png" /><figcaption>Failure decisions for the hypothetical video-export workflow. The cancellation contract determines which transitions remain allowed.</figcaption></figure><p>The inbox catches duplicate delivery. Operation identity and state checks catch different events that are no longer relevant. Both are necessary.</p><h3>Waiting is part of the persisted state</h3><p>“Retry in ten minutes” creates an obligation that outlives the process holding the timer.</p><p>In a database implementation, persist next_attempt_at and let a scheduler claim due work. Check the deadline again when dispatching; the queue may have delayed a job beyond its useful lifetime. Record why a retry is scheduled and whether a human can resume it. A dead-letter topic alone is not an answer to those questions.</p><p>Avoid treating all waits as failures. Waiting for footage to become available is expected progress. Repeated authorization failures at a storage service are not. A transient network timeout, missing recording interval, and invalid export specification need different retry policies.</p><p>There is also a product decision hidden in “deadline.” Does it mean no new work after that time, or no result should become visible afterward? A render already running at expiry can still produce a file. Under a no-new-work policy, an already authorized step may finish, while later steps remain blocked. Under a no-visible-result policy, the publication path must also check expiry before making the artifact available; delaying the scheduler’s expiry event must not extend the deadline.</p><p>Neither rule erases compute already consumed. Record that cost and the eventual artifact outcome even if the customer-facing export ends as expired. Schedule cleanup separately and make it repeatable. Otherwise a workflow that looks terminal in the UI can leave storage and render jobs behind indefinitely.</p><p>These details are manageable for a small workflow. They become a substantial subsystem when every product flow has different branches, waiting conditions, and recovery actions.</p><h3>Where a workflow engine earns its place</h3><p>A workflow engine becomes attractive when the team is repeatedly implementing durable waits, execution history, retries, and resumption across many flows. <a href="https://docs.temporal.io/workflow-execution">Temporal’s workflow execution model</a> is one example: it provides durable execution through recorded history and replay, rather than requiring the application to assemble those mechanics around every consumer.</p><p>It does not make the renderer’s lost-response problem disappear. Temporal’s <a href="https://docs.temporal.io/activity-definition">Activity documentation</a> explicitly explains why Activities need idempotency: an external action may finish while its completion is never reported. Retrying that Activity still needs the same business operation identity.</p><p>Adopting an engine also brings deployment and versioning obligations. A workflow waiting for days may resume under changed code. A database state machine needs a migration policy for those old jobs; a replay-based engine needs changes compatible with its execution rules. Include that work in the decision.</p><p>Kafka can continue carrying facts that multiple independent systems need: a recording became available, an export was requested, an artifact was produced. The workflow owner decides what should happen next for a particular export. Those responsibilities can coexist.</p><p>For a straightforward consume-transform-produce pipeline, Kafka’s processing model may cover the requirement well. For a few short business flows, an explicit database state machine may be sufficient. When their recovery machinery starts dominating feature work, a workflow platform deserves a serious evaluation.</p><p>I would make the choice by taking one cancelled export and asking the system to explain it: what was authorized, which external work may still be running, what will happen if the worker restarts, and whether a replay can send the email again. If answering requires reading five consumers and interviewing whoever last repaired the database, the workflow already exists. Its owner and rules are just difficult to find.</p><p><em>I’m Burak Hamuryen, a software engineer in Berlin working on distributed systems and real-time video infrastructure. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e7f424baa3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Is Self-Hosting AI Actually Cheaper?]]></title>
            <link>https://medium.com/@hamuryen/when-is-self-hosting-ai-actually-cheaper-5339fec9b579?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/5339fec9b579</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[self-hosting]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-10-12T08:01:02.171Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A monthly cost model, and the workload assumptions that can make it useless.</em></p><figure><img alt="A balance scale weighs a local GPU server against a blue cloud and usage tokens, illustrating the tradeoff between ownership and pay-per-use costs." src="https://cdn-images-1.medium.com/max/1024/1*T42rERl0Y4UZJz0nMDXa5w.png" /><figcaption>A lower cost per token only helps if the workload can carry the cost of owning and operating the server.</figcaption></figure><p>At 100,000 requests a month, the local server in the example below costs $293.98. The API costs $300.</p><p>That looks like a win for self-hosting. Four more hours of maintenance turn the local bill into $593.98. No hardware changed. No model got slower. We simply charged for more of the work.</p><p>These are deliberately hypothetical numbers, not a quote for a particular GPU or model. I want to make the decision inspectable before arguing about the answer.</p><p>A recent <a href="https://www.reddit.com/r/LocalLLaMA/comments/1ww2jsu/selfhosting_ai_does_not_save_money_and_i_do_it/">discussion about the cost of self-hosting AI</a> captures why these comparisons become heated. One person already owns the machine. Another is buying it for this purpose. Someone values keeping personal data at home more than the price difference. Someone else needs a model their hardware cannot run. They can all do the arithmetic correctly and reach different conclusions.</p><p>My background is in backend services, GPU video pipelines, and deployments spanning cloud, customer networks, and edge devices. The part of this question I recognize is capacity: what useful work does the machine deliver, under what conditions, and who keeps it working?</p><h3>Agree on what counts as a successful request</h3><p>Before comparing prices, give both options the same job.</p><p>For a document extraction service, that could mean a defined mix of document lengths, required fields, an acceptable error rate, and a response deadline. For an interactive assistant, the time before the first token appears and the pauses during generation may matter as much as total completion time.</p><p>The same model and precision are a clean starting point when both providers offer them. Different models can still be compared, but then the comparison is between systems that meet the same application requirements. A cheaper answer that needs a second model to repair it belongs in the bill too.</p><p>This changes the denominator. Cost per generated token is useful for understanding a serving engine. Cost per accepted extraction, resolved request, or completed task is closer to what the application buys.</p><p>Keep rejected outputs, retries, and fallbacks in the numerator. If twenty percent of local results go to an external model for repair, the local system has an API bill. If the API needs retries, it should carry those costs as well.</p><p>For the worked example, assume every request completes successfully in one attempt on either system, with equivalent acceptable output. That is a simplifying assumption to replace with measured behavior, not a property of local or hosted models.</p><h3>A small model you can change</h3><p>Use one request shape: 4,000 input tokens and 500 output tokens. Assume an API price of $0.50 per million input tokens and $2 per million output tokens. <strong>These are illustrative rates, not current prices for a named provider.</strong></p><p>The API cost per request is:</p><pre>(4,000 × $0.50 + 500 × $2) / 1,000,000 = $0.003</pre><p>Actual provider billing needs more care. For example, <a href="https://aws.amazon.com/bedrock/pricing/">Amazon Bedrock pricing</a> distinguishes model-specific input and output rates, batch processing, and applicable cache pricing. Copy the billing rules for the service you would actually use; do not substitute the price of a consumer chat subscription.</p><p>Now give the local option an explicit budget. Compare costs that differ between the options: the two operations hours below are additional work for local hosting relative to the API, and the $20 covers local-specific recurring overhead. Shared application development and operations are omitted from both sides. The dollar totals are comparable incremental costs, not the entire application’s operating budget.</p><figure><img alt="Illustrative assumptions: $3,600 machine over 36 months; 730 powered-on hours monthly; 100 W idle and 350 W active; electricity $0.30/kWh; 2 extra operations hours at $75/hour; $20 other monthly costs; 1 accepted request/second." src="https://cdn-images-1.medium.com/max/1024/1*66IfSkGBti-h1IwY2u4G1g.png" /><figcaption>Illustrative local-host assumptions. Illustrative assumptions; no measured hardware performance or vendor prices.</figcaption></figure><p>That last row is particularly important. It is <strong>an assumed capacity for this calculation</strong>, not a claim that a $3,600 machine can serve this workload at that rate. The model has no named hardware, model weights, quantization, or benchmark behind it. If your chosen system cannot meet the quality and latency requirements, a favorable result from this table is irrelevant.</p><p>The monthly fixed cost is:</p><pre>Hardware:       $3,600 / 36                  = $100.00<br>Idle energy:    0.100 kW × 730 h × $0.30/kWh =  $21.90<br>Operations:     2 h × $75/h                 = $150.00<br>Other:                                       $20.00<br>Total:                                      $291.90</pre><p>Idle electricity already covers the entire month. During active time, add only the extra 250 W, otherwise the idle portion gets charged twice.</p><p>At one request per second, the assumed incremental electricity cost is:</p><pre>(0.250 kW × $0.30/kWh) / 3,600 requests/h<br>    = $0.000020833 per request</pre><p>The resulting monthly comparison is:</p><figure><img alt="Illustrative monthly local versus API costs: 10,000 requests, $292.11 versus $30; 100,000, $293.98 versus $300; 500,000, $302.32 versus $1,500." src="https://cdn-images-1.medium.com/max/1024/1*GhwkCtoOWK19PX3C1OAXDw.png" /><figcaption>Monthly accepted requests: 10,000, 100,000 and 500,000. Costs use illustrative assumptions; extra local maintenance can reverse a narrow saving.</figcaption></figure><p>This is a single-host, steady-workload accounting case. It excludes initial integration effort, financing, taxes, unexpected repairs, cooling beyond the measured machine power, and redundancy. Production planning should add those costs to whichever side incurs them. It also assumes the API has enough quota to serve the workload without a separate capacity commitment.</p><p>The small <a href="https://gist.github.com/hamuryen/06345e4ca3dcff0216e4e9eb78e5214c">Python calculator accompanying this article</a> reproduces the table. Every input can be changed:</p><pre>python3 ai_hosting_costs.py --check<br>python3 ai_hosting_costs.py --ops-hours 6 --requests 100000</pre><p>It requires only the standard library and makes no network requests.</p><h3>Find the assumption that changes the decision</h3><p>Write local cost as F + vN, where F is monthly fixed cost, v is incremental cost per accepted request, and N is accepted requests per month. Write API cost as aN.</p><p>If a &gt; v, the arithmetic break-even is:</p><pre>N = F / (a - v)</pre><p>For the example, it is approximately 97,980 requests per month. If the API unit cost is no higher than the local variable cost, there is no volume at which this positive fixed cost gets recovered through cheaper requests.</p><p>This line only applies while one host can serve the workload. If the required arrival rate exceeds its sustainable capacity, adding another machine introduces another purchase, idle-power budget and potentially more operations work. Local cost then rises in steps. Extrapolating the first host’s cheap incremental requests past that boundary understates the bill.</p><p>Zero resale value is also a deliberate assumption. An expected resale value reduces the hardware component to (purchase − resale) / months, moving break-even in favor of local hosting. Use a realistic estimate for the end of your ownership period, including the cost of selling or replacing the machine.</p><p>At 100,000 requests, the apparent advantage is about six dollars a month. That is too small to survive much uncertainty. Raising operations from two hours to six increases the fixed cost to $591.90 and moves break-even to roughly 198,680 requests.</p><p>The API rate has a similarly large effect. Holding the workload and local assumptions fixed, halving both token prices moves break-even to about 197,341 requests; doubling them brings it down to about 48,820. At 100,000 requests, active electricity contributes only $2.08 of the $293.98 local total. In this particular model, arguing over a few watts matters much less than choosing the right API comparison and accounting for engineering time.</p><p>Changing output length is more involved: it changes the API bill and the local service rate. Do not increase output tokens in the calculator while keeping throughput fixed unless a measurement supports that combination.</p><p>Changing only the assumed throughput illustrates a different sensitivity:</p><figure><img alt="At 0.2, 1 and 3 assumed requests/second, break-even volumes are 100,800, 97,980 and 97,526 requests/month. Serving 100,000 requests needs 138.89, 27.78 and 9.26 active hours respectively." src="https://cdn-images-1.medium.com/max/1024/1*9vtmx63gODsuxr1zgj-qaA.png" /><figcaption>Rows assume 0.2, 1 and 3 accepted requests/second. These are capacity scenarios, not measured hardware results.</figcaption></figure><p>The financial crossing point moves little, while required machine time changes fifteenfold. These are still hypothetical capacities with fixed costs and power held constant; buying different hardware would change those assumptions too. They show why a reassuring cost calculation can coexist with a service that cannot keep up.</p><p>The additional operations budget covers the difference in maintaining the serving stack, evaluating updates, investigating failures, and restoring service. Hosted APIs require engineering too; the example assumes that shared effort cancels. If your API option also has separate fixed charges, use the difference between the two fixed-cost totals in the break-even calculation rather than treating the API as free to operate.</p><p>For an existing workstation, the next decision may be much smaller: run tonight’s job locally or pay an API. Purchase price can reasonably be sunk for that decision. It remains relevant when deciding to buy a replacement, reserve the machine for inference, or deploy another site. I would keep a marginal-cost calculation and an ownership-cost calculation beside each other rather than use one to answer both questions.</p><h3>Monthly volume can hide an impossible service</h3><p>The table’s 500,000 requests use about 139 active hours at the assumed rate. Spread over a month, that sounds comfortable.</p><p>Suppose most arrive during a two-hour window each weekday. With 22 working days, they now have 44 hours in which to run. The average arrival rate inside those windows is about 3.16 requests per second, before accounting for bursts. A machine sustaining one request per second cannot keep up during that period.</p><p>For an overnight batch, a backlog may be fine. For a live assistant, it may violate the response deadline. An hourly cost calculation cannot decide that distinction for you.</p><p>Batching also complicates the assumed service rate. TNG’s <a href="https://huggingface.co/blog/tngtech/llm-performance-prefill-decode-concurrent-requests">analysis of concurrent LLM serving</a> describes how admitting prompt-processing work can interfere with ongoing token generation. A higher aggregate token rate can coexist with a less responsive individual session. Use the throughput that meets your latency requirement, not the highest number printed by a benchmark.</p><p>In a trial, replay the arrival pattern and prompt-length distribution you expect to serve. Include long inputs, cancellations, and cache misses. Report queueing and the slower responses, not just an average from requests issued one at a time. <a href="https://docs.vllm.ai/en/latest/usage/metrics/">vLLM exposes separate metrics</a> for queue time, time to first token, token-generation latency, and end-to-end request time; those distinctions are useful even with another server.</p><p>The calculator rejects demand above the physical ceiling of its assumed rate multiplied by powered-on hours. Passing is only a necessary condition, never a feasibility verdict. Even the 500,000-request example passes that check and fails the 44-hour service window. A blanket utilization allowance cannot fix this: capacity planning needs the arrival pattern, tolerated backlog, maintenance windows and response deadline together.</p><h3>Availability changes the bill before the first outage</h3><p>A single workstation and a managed endpoint may satisfy very different service expectations.</p><p>If maintenance can wait until morning, one local machine may be sufficient. If a customer workflow must continue through a machine failure, account for spare capacity, recovery time, and the person responsible for using it. An API fallback may be cheaper than a second local host, but only if sending the data there is permitted and the application accepts its output.</p><p>An API is not an unlimited backup generator. Check quotas and the failure behavior of your client. The worst time to discover an insufficient rate limit is when every local request moves to the fallback at once.</p><p>For a fleet of customer installations, repeat this calculation per site. A hundred underused devices do not become one well-utilized device because their totals look healthy on a dashboard. Capacity can only be shared where data movement, network access, and response requirements allow it.</p><p>That is where my experience with on-premise and edge systems shapes the question. A locally processed workload might be worth paying more for because it must continue without a WAN connection or keep data inside a customer’s network. Evaluate that requirement separately from token cost.</p><h3>What I would need before buying the machine</h3><p>I would want a workload sample with an acceptance test, a measured service rate under its latency limit, and a monthly arrival profile. Then I would run the cost model across plausible values for maintenance time, electricity, API pricing, and hardware lifetime.</p><p>If the answer changes after adding four hours of work, I would treat that as a close decision. If it stays favorable across the realistic range, the hardware proposal has a stronger basis.</p><p>For the worked example, I would not buy a machine on the strength of a six-dollar monthly saving. I would first replace the assumed service rate with a measurement, price the necessary availability, and check whether the result survives a less favorable maintenance month. Those changes could settle the decision before any argument about which deployment model is inherently cheaper.</p><p><em>I’m Burak Hamuryen, a software engineer in Berlin working on distributed systems and real-time video infrastructure. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5339fec9b579" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python 3.15 Lazy Imports: Where the Startup Cost Goes]]></title>
            <link>https://medium.com/@hamuryen/python-3-15-lazy-imports-where-the-startup-cost-goes-966c2b3f3b41?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/966c2b3f3b41</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 08:01:03 GMT</pubDate>
            <atom:updated>2026-10-10T08:01:03.834Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A small lazy-import experiment, and the measurements a release benchmark cannot make for you.</em></p><figure><img alt="Five amber blocks sit before a blue gate on one track and after it on another, illustrating the same initialization work moving to a later stage." src="https://cdn-images-1.medium.com/max/1024/1*SHlHav2S_pDKcVrSprwFiA.png" /><figcaption>The same initialization work can move past readiness and into the first useful operation.</figcaption></figure><p>In a small experiment prepared for this article, changing one import to a lazy import moved roughly 26 milliseconds of work past a simulated readiness point.</p><p>The first useful operation still finished after about 30 milliseconds.</p><p>Both results are real. They describe different parts of the same process. That distinction matters when deciding what <a href="https://www.python.org/downloads/release/python-3150/">Python 3.15, released on October 9</a>, can do for a backend service.</p><p>The release includes work on the experimental JIT, free-threaded builds, and explicit lazy imports. These features affect different costs. A service can benefit from one and have little reason to use another. Before assigning an expected percentage improvement to an upgrade, I would want to know where the service spends its time and when that time is paid.</p><p>Lazy imports are the measured case here. JIT and free-threading appear later to explain why this result cannot stand in for an evaluation of the whole upgrade.</p><p>My perspective comes from backends that coordinate other systems, including native code and video infrastructure. In that setting, “Python is slow” is an incomplete diagnosis. It might mean Python code is consuming a core. It might mean a worker is waiting for storage. It might mean a process takes too long to become useful after deployment. Those need different experiments.</p><h3>Measure readiness and the first useful operation separately</h3><p><a href="https://peps.python.org/pep-0810/">PEP 810</a> introduces explicit lazy imports. At module scope, this declaration defers loading until the imported name is used:</p><pre>lazy import email.parser<br># Other startup work could happen here.<br>message = email.parser.Parser().parsestr(&quot;Subject: Example\n\nBody&quot;)</pre><p>Ordinary imports retain their normal behavior under the default import mode. You choose which imports to defer. A module that is never used can avoid its initialization entirely; a module used immediately after readiness still has to load.</p><p>To examine that boundary, the <a href="https://gist.github.com/hamuryen/b2a4dfc15af70d141043a76305497569">companion script</a> runs eager and lazy versions in fresh processes using the same interpreter. Each process records four intervals:</p><ol><li>From just before the import declaration to a synthetic “ready” marker immediately after it.</li><li>From that marker through the first parsed message.</li><li>The second parsed message.</li><li>The combined time through the first parsed message.</li></ol><p>There is no web server in this experiment. “Ready” is a marker in a short script, not a successful HTTP health check. Interpreter startup and result serialization are outside the measured window.</p><p>The run used final CPython 3.15.0, built from the official source archive on macOS ARM64 with Apple Clang 21.0.0 from Xcode. The configure flags were --without-ensurepip --disable-test-modules; PGO and LTO were not enabled. The GIL was enabled and the build had no JIT. Five warmups per case were discarded, followed by 60 observations per case in a shuffled order.</p><figure><img alt="Python 3.15 timing comparison. Eager versus lazy median readiness: 26.158 and 0.000709 milliseconds. Time through the first result: 30.294 and 30.197 milliseconds. Q1–Q3 ranges shown; 60 observations per case." src="https://cdn-images-1.medium.com/max/1024/1*ayS6hQA4IuQ2gybMrRNVZQ.png" /><figcaption>Median timings with Q1–Q3 ranges, in milliseconds. CPython 3.15.0; 60 observations per case.</figcaption></figure><p>These are measurements from one local run on October 9, 2026. The Q1–Q3 ranges show the middle half of observations, not a confidence interval. The combined interval is measured directly; adding separate medians need not reproduce its median. The first-call window also includes a small sys.modules membership check that verifies whether the import had already happened at readiness.</p><p>The <a href="https://gist.github.com/hamuryen/b2a4dfc15af70d141043a76305497569#file-python315-import-results-json">raw observations and build metadata</a> accompany the script. Each child used isolated mode, disabled bytecode writes, and explicitly selected normal import mode. Existing standard-library bytecode was left in place, and warmups primed filesystem caches. This is a fresh-process experiment with warm caches, not a cold-disk test. CPU frequency, thermals, and background activity were not controlled. The sub-microsecond declaration timing is close enough to measurement overhead that I would only read it as negligible here.</p><p>The result supports a narrow conclusion: for this example, the lazy declaration shifts almost all of the import cost across the ready marker. It does not demonstrate a meaningful reduction in time to the first result, and it says nothing about HTTP throughput or Python 3.14 versus 3.15.</p><h3>Warm the path you intend to serve</h3><p>Even with the eager import, the first parse takes roughly four milliseconds while the second takes about 0.018 milliseconds. There is still work left after importing the top-level parser.</p><p>A separate diagnostic run with -X importtime shows email.message, email._encoded_words, and email.iterators loading during the first parse. The <a href="https://github.com/python/cpython/blob/v3.15.0/Lib/email/feedparser.py">3.15 implementation of </a><a href="https://github.com/python/cpython/blob/v3.15.0/Lib/email/feedparser.py">FeedParser</a> explains why: with the default policy and no supplied message factory, its constructor imports Message inside the function. Eagerly importing email.parser does not execute that constructor.</p><p>You can inspect the same boundary without changing the benchmark:</p><pre>python3.15 -I -B -X importtime -c &#39;import email.parser; print(&quot;BEFORE_FIRST_PARSE&quot;, file=__import__(&quot;sys&quot;).stderr); email.parser.Parser().parsestr(&quot;Subject: Example\n\nBody&quot;)&#39;</pre><p>Imports printed after the marker occur on first use. This diagnostic adds instrumentation, so its timings are separate from the table; it identifies deferred work without assigning every fraction of the original four milliseconds to an import. The <a href="https://gist.github.com/hamuryen/b2a4dfc15af70d141043a76305497569#file-python315-first-use-import-trace-txt">captured trace</a> accompanies the results.</p><p>For this dependency, “we imported it during startup” is an incomplete warmup check. Exercise the path the service actually needs. Other modules can behave differently; this single-module experiment establishes the mechanism, not its prevalence across an application.</p><h3>Decide who should pay for initialization</h3><p>That shift can still be useful.</p><p>Imagine a command-line tool with a lightweight status command and a rarely used report command. Loading the report stack for status is unnecessary work. Deferring it can eliminate that cost for the entire invocation.</p><p>A backend has a more complicated choice. Suppose most requests use a lightweight route, while occasional requests generate reports. Deferring the report dependency can reduce startup work. The first report request then inherits the initialization cost. If many workers have just been replaced, many first requests may encounter it.</p><p>Whether that is acceptable depends on the service’s contract. If reports are queued and complete asynchronously, a little extra initialization may be harmless. If the first report has the same latency deadline as every later one, warming that dependency before accepting report traffic may be the better policy.</p><p>Readiness should reflect the capability you intend to offer. A process returning 200 OK from a trivial health endpoint does not establish that its critical request path can import its dependencies, load configuration, and perform the required work.</p><p>Lazy initialization also changes when failures and side effects occur. A missing dependency can fail at first use rather than startup. Registration code that runs during import does not run until the import is resolved. If a plugin registry depends on those side effects, deferring an import can change behavior, not just timing. That follows from the <a href="https://peps.python.org/pep-0810/">semantics specified in PEP 810</a>; test those paths before broadly changing import declarations.</p><p>Start with genuinely optional features, then make the warmup policy explicit for required capabilities. The service still needs to become ready to do what its callers expect.</p><h3>Read the JIT result with its denominator attached</h3><p>The <a href="https://docs.python.org/3.15/whatsnew/3.15.html#upgraded-experimental-jit-compiler">3.15 release notes</a> report geometric-mean gains on pyperformance of roughly 7–8% on x86-64 Linux and 11–12% on AArch64 macOS, against the respective optimized interpreter baselines. The macOS comparison uses the tail-calling interpreter. These are upstream results for the experimental JIT, not measurements of this article&#39;s example and not a promise that upgrading any 3.14 service yields those gains. The notes also report variation across individual benchmarks, including regressions.</p><p>A benchmark suite is useful evidence about the implementation. A backend response includes work outside that implementation.</p><p>Take a deliberately simplified request: 10 milliseconds executing Python code and 90 milliseconds waiting for a database. Choose a hypothetical 20% improvement in Python execution speed, unrelated to the upstream percentages above. That portion falls to about 8.33 milliseconds. The whole request falls from 100 to 98.33 milliseconds: about a 1.7% latency reduction.</p><p>That is arithmetic under fixed assumptions, not a service benchmark. It assumes serial work, unchanged database time, and no queueing. Near saturation, reducing CPU demand can also reduce waiting in a worker queue, so the end-to-end effect may be larger. Conversely, a new bottleneck can limit throughput. Measure at the concurrency that matters.</p><p>For a JIT evaluation, separate startup, warmup, and sustained execution. A short-lived job and a long-running worker provide different opportunities to recover compilation work. Include memory use and CPU per completed request alongside latency. A lower median that increases memory enough to reduce worker density might be an unattractive trade in a constrained deployment.</p><p>Compare equivalent builds: a 3.14-to-3.15 experiment needs matching optimization flags and the same machine and workload. A source build without PGO against an optimized distributor build changes more than the Python version.</p><h3>Free-threading needs a workload and dependency check</h3><p>A free-threaded build addresses another question: can multiple Python threads execute the relevant work in parallel, and does that improve this application?</p><p>The <a href="https://docs.python.org/3.15/howto/free-threading-python.html">Python 3.15 free-threading guide</a> explains both the build distinction and an important compatibility behavior: importing an extension that does not declare free-threading support can re-enable the GIL. Check the running process after loading the application’s actual dependencies. Do not infer its state from the installer you selected.</p><p>The workload matters: Python computation, native libraries with their own thread pools, and network waits offer different opportunities. Shared state needs attention too. A cache can have thread-safe individual accesses while a check-then-initialize sequence still creates the same resource twice. Successful concurrent requests alone do not establish correctness.</p><p>Compare a fixed CPU and memory budget. An existing deployment may already use multiple worker processes to occupy several cores. The relevant result is useful work per allocated resource under the same latency requirement.</p><h3>A useful upgrade result fits on one page</h3><p>For a real backend, keep readiness, first-use latency and steady-state behavior beside the compatibility results. Hold the workload and resources fixed and change one feature at a time. A version upgrade, JIT activation and a move to free-threading deserve separate comparisons.</p><p>To reproduce the lazy-import experiment with a final Python 3.15 interpreter:</p><pre>python3.15 python315_imports.py &gt; python315-import-results.json</pre><p>Its most useful number is the pair of roughly 30-millisecond totals. Without them, the readiness improvement would sound much more impressive than the change experienced by the first caller.</p><p>For a rarely used command, avoiding the import could be the whole win. For a backend that needs the module on its first request, I would decide explicitly whether startup or the caller should pay. That is the sort of answer I want from an upgrade experiment: a measured change tied to a workload, with the displaced cost still visible.</p><p><em>I’m Burak Hamuryen, a software engineer in Berlin working on distributed systems and real-time video infrastructure. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=966c2b3f3b41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Camera Is Online. Is the Video Still Live?]]></title>
            <link>https://medium.com/@hamuryen/your-camera-is-online-is-the-video-still-live-65403083c049?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/65403083c049</guid>
            <category><![CDATA[rtsp]]></category>
            <category><![CDATA[streaming-video]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 13:01:04 GMT</pubDate>
            <atom:updated>2026-09-21T13:01:04.558Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A connected session tells you much less than an advancing video stream.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dHehevhsKVT4P07jBl8dg.png" /><figcaption><em>The connection is healthy. The frames still have somewhere to go.</em></figcaption></figure><p>A camera can answer requests while its video stops moving. A relay can receive packets while a viewer gets no new frames. A player can run smoothly while showing video that is several seconds old.</p><p>All three can sit behind the same green “online” label.</p><p>I’ve worked on video systems that bridge camera protocols, native services, and browser playback. One thing I want from their monitoring is a clear answer to a small question: where did progress stop?</p><p>That answer needs more than a successful connection or a running process. It needs evidence from the media path.</p><p>Here is how I would build that evidence, using transport, timing, decoding, and playback signals. The goal is to detect delivery problems without interpreting what appears in the picture.</p><h3>Give “online” a smaller meaning</h3><p>An online state can be useful. It might mean the service recently contacted the camera, an RTSP session exists, or the transport remains connected.</p><p>Keep that meaning. Add separate observations for the video.</p><p>The path might contain a camera, an ingest service, a relay, a recorder, and a browser. Each can be running while the next stage waits. A status endpoint only proves whatever work the endpoint actually checks.</p><p>MediaMTX provides a useful example of separate transport observations. Its metrics include session state, inbound and outbound traffic, RTP packet loss, and packet errors. These give more detail than a connection count alone. <a href="https://mediamtx.org/docs/features/metrics">1</a></p><p>They still describe the server’s view. A relay that forwards compressed video without decoding it cannot report whether a downstream decoder produced a usable frame. A server that sent bytes cannot prove the browser presented them.</p><p>Keep those limits visible. “Receiving video packets” is an honest and useful status. Calling it “live playback healthy” adds a claim that needs another measurement.</p><h3>Track the last useful progress at each stage</h3><p>For each active stream, record when useful work last advanced. The exact measurements depend on what the application does, but the questions are stable:</p><p>StageEvidence of progressWhat it does not proveIngestNew video media packets arriveA complete frame can be decodedDecodeThe decoder produces another frameThe viewer presents itPlaybackA new frame is submitted for presentationIt was captured recentlyRecordingRecorded media time advances in completed outputThat output survives every storage failureMonitoringA fresh observation arrivesThe stream itself is healthy</p><p>Keep audio and video separate. Audio packets can continue while the video track stalls. Keep control traffic separate too; a keepalive is not video progress.</p><p>For a local stage, the basic age calculation is small:</p><pre>progress age = current monotonic time - last local progress time</pre><p>Both times must come from the same clock domain. A monotonic clock measures elapsed time without depending on wall-clock corrections. Raw monotonic timestamps from different machines cannot be subtracted this way.</p><p>A stage that has never produced output needs a startup state, not a fabricated “last frame” timestamp. After a reconnect, begin a new observation period and retain the previous failure in the history.</p><p>This turns a vague complaint into something you can inspect. In a constructed example, packets and decoded frames keep advancing, while presentation has not advanced for several seconds. I would first investigate the path from decoded output to the player. Restarting the camera would be a poorly targeted first response.</p><h3>Smooth playback can still be late</h3><p>There are two different questions: is video advancing, and how old is it?</p><p>A player can display 30 frames per second from a queue that is three seconds behind the source. Its frame rate looks healthy. Its live delay does not.</p><p>You need an age measurement to tell those cases apart. Unfortunately, a media timestamp is not automatically a capture time you can subtract from the current clock.</p><p>RTP timestamps use a media clock with an arbitrary starting point. RTCP sender reports can associate an RTP timestamp with an NTP-format timestamp, but that mapping still depends on the sender’s clock and timestamp behavior. Jitter measures variation in transit timing; it is not a measurement of total end-to-end delay. <a href="https://www.rfc-editor.org/rfc/rfc3550">2</a></p><p>Name each measured delay after its actual endpoints. “Time from gateway ingest to gateway output” is useful. Calling it “camera-to-screen latency” would hide the time spent before and after the gateway.</p><p>Where a trustworthy capture-time mapping is available, use it and document its limits. Where it is missing, track local queue age and stage delay, and leave absolute capture freshness unknown.</p><p>An honest partial measurement gives an operator somewhere to start. A precise-looking number built from unrelated clocks can send the investigation in the wrong direction.</p><p>There is another limit worth stating. A camera could repeatedly encode the same picture while sending valid packets and advancing timestamps. Transport and timing signals alone cannot reliably distinguish that from a legitimate still scene. This monitoring design detects delivery and progress failures; it does not establish whether the pictured scene is changing.</p><h3>Measure the player’s side of the connection</h3><p>For WebRTC playback, the statistics API exposes several stages separately. Received frames, decoded frames, packet timing, and rendering-related freeze or pause measurements can help narrow down a problem. Availability needs checking in the browsers you support. <a href="https://www.w3.org/TR/webrtc-stats/">3</a></p><p>Some of those measurements describe completed intervals. The specification updates pause and freeze information around rendered frames; a pause count increments when rendering resumes after the pause. I would not rely on that counter alone to detect a stall that is still happening. <a href="https://www.w3.org/TR/webrtc-stats/">3</a></p><p>The page needs a current progress observation as well.</p><p>requestVideoFrameCallback() runs when a new frame is sent to the compositor and exposes presentation-related metadata. It can help track whether the video element is advancing. The callback runs on the main thread, and the API does not guarantee exact synchronization with physical display output. <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement/requestVideoFrameCallback">4</a></p><p>That distinction matters during diagnosis. If the page’s main thread is blocked, the callback can be late too. If the user paused playback or the page is in the background, the application’s expectations need to change.</p><p>Report playback intent and page state alongside the timing. “Expected to play, visible, no presentation progress” is much more useful than “no callback.”</p><p>Client reports also have a delivery path of their own. If those reports stop reaching the backend, the backend has lost visibility. It has not proved that the camera stopped sending video.</p><h3>Turn observations into states carefully</h3><p>A single timeout for every stream is tempting. It also ignores how streams behave.</p><p>A low-frame-rate source has a different expected gap from a 30 fps preview. A newly connected decoder may need time to produce its first frame. An on-demand stream may correctly be idle until someone starts watching it.</p><p>Begin with explicit expectations for each stream class: whether media should be flowing, how often progress is expected, and how much startup time is allowed.</p><p>The active stream can then move between a few states:</p><ul><li><strong>Starting:</strong> the stream is expected, but it has not established normal progress yet.</li><li><strong>Healthy:</strong> the required observations are fresh and within their budgets.</li><li><strong>Degraded:</strong> progress continues, but a delay or error budget is exceeded.</li><li><strong>Stalled:</strong> an expected stage has stopped advancing beyond its allowed gap.</li><li><strong>Unknown:</strong> the observations needed to make the decision are missing or stale.</li></ul><p>An intentionally idle stream sits outside the active-stream evaluation. It should not create a stream failure merely because no viewer requested it.</p><p>The thresholds should come from the service requirement and the stream’s expected behavior. I would record the reason for every transition: ingest stopped, decode stopped, presentation stopped, or delay grew too large.</p><p>Require sustained recovery before clearing an alert. One packet after a long silence is evidence of contact, but it does not establish stable playback.</p><p>The classifier itself should not have to watch every frame centrally. Each component can maintain its local progress and send compact summaries. Detailed timing can be retained around a transition, when it is most useful for diagnosis.</p><h3>Read counters across a useful interval</h3><p>A total packet-loss counter answers how much loss has accumulated over its lifetime. The change over a recent interval helps answer what is happening now.</p><p>Compare observations from the same stream session. A reconnect, process restart, or replacement statistics object can reset a counter. Keep the session identity with the samples and start a new baseline when it changes. Do not treat a reset as a sudden negative rate or uninterrupted success.</p><p>Preserve incident history outside the live session object. Reconnecting can restore the stream while making its new counters look perfectly clean.</p><p>Loss, jitter, and errors help explain degraded delivery, but no single one is a universal failure threshold. A receiver may recover some lost data. A stream can also stall without packet loss if a downstream stage stops consuming it.</p><p>GStreamer’s RTP jitter buffer illustrates the tradeoff: it reorders packets and waits within a configured latency budget. Waiting can help with late arrivals, while adding delay to the path. Its settings and drop observations belong in the investigation. <a href="https://gstreamer.freedesktop.org/documentation/rtpmanager/rtpjitterbuffer.html">5</a></p><p>Look for changes together: rising queue age, slower decode output, late packets, and stalled presentation. Agreement between independent observations is more useful than a red threshold on an isolated graph.</p><h3>Recording needs its own health signal</h3><p>A live viewer and a recorder can fail independently. A healthy player does not prove the recording is progressing, and a growing file does not prove the latest video is available for playback.</p><p>For a segmented recorder, I would track the most recently completed segment, the media interval it covers, and whether it can be opened and decoded. I would separately track whether that segment reached the intended storage destination.</p><p>This check does not need to interpret the frames. It checks the container, timestamps, and decodability. It should also account for audio-only progress rather than assuming any file growth means new video was saved.</p><p>The expected completion interval depends on the recording format and segment policy. An unfinished segment can be normal. A health rule that ignores that will produce false alarms at regular intervals.</p><p>A slow recorder can also affect another branch if they share work or buffers. GStreamer’s tee documentation calls for a separate queue or multiqueue in each branch so a blocked branch does not immediately stall the others. Finite queues still need an overload policy once they fill. <a href="https://gstreamer.freedesktop.org/documentation/coreelements/tee.html">6</a></p><p>Missing recorded time should be explicit. Buffering, rejected work, and storage failure should lead to a visible result that the operator can distinguish from a complete recording.</p><h3>Test the green status, not just the reconnect</h3><p>Before trusting these states, I would create failures in a small test setup and check the reported timeline.</p><p>Start with a sender that can stop video while keeping its control path alive. The expected result is a media-progress failure even if the connection stays open.</p><p>Then hold packets long enough to create delay while allowing them to keep arriving. Check that advancing counters do not hide old video. Slow a downstream consumer separately, so the monitoring can distinguish ingest progress from output progress.</p><p>Test a slow recording destination while watching live playback. Pause the player deliberately. Put the page in the background. Stop the component that reports metrics. Each case should produce a reason that matches what actually happened, including “unknown” when observation is lost.</p><p>Finally, reconnect the stream and let it recover. Check startup handling, reset counters, alert clearing, and retention of the previous gap. A test that ends at the first successful reconnect misses much of the behavior an operator will depend on.</p><p>These tests establish what the health labels mean. They also expose cases where the application does not yet have enough information to make a reliable claim.</p><p>I would still keep the small green connection light. Beside it, I would want to see where video last advanced, how much delay we can actually measure, and when those observations were updated.</p><p>That gives the next engineer something better than “the camera is online.” It gives them a place to look.</p><h3>Sources</h3><ol><li><a href="https://mediamtx.org/docs/features/metrics">MediaMTX: Extract metrics</a>.</li><li><a href="https://www.rfc-editor.org/rfc/rfc3550">RFC 3550: RTP — A Transport Protocol for Real-Time Applications</a>, especially sections 5.1 and 6.4.1.</li><li><a href="https://www.w3.org/TR/webrtc-stats/">W3C: Identifiers for WebRTC’s Statistics API</a>, including inbound RTP and video pause/freeze definitions.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement/requestVideoFrameCallback">MDN: HTMLVideoElement.requestVideoFrameCallback()</a>.</li><li><a href="https://gstreamer.freedesktop.org/documentation/rtpmanager/rtpjitterbuffer.html">GStreamer: rtpjitterbuffer</a>.</li><li><a href="https://gstreamer.freedesktop.org/documentation/coreelements/tee.html">GStreamer: tee</a>.</li></ol><p><em>I’m Burak Hamuryen, a software engineer in Berlin working on distributed systems and real-time video infrastructure. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65403083c049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Years, 6 Languages, 1 Monorepo: What I’d Do Differently]]></title>
            <link>https://medium.com/@hamuryen/4-years-6-languages-1-monorepo-what-id-do-differently-004795fac1a3?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/004795fac1a3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[monorepo]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 13:01:03 GMT</pubDate>
            <atom:updated>2026-09-17T13:01:03.028Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Shared code made integration easier. Keeping everyday work fast took more care.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNrJJkqYUSlIf5MsjIJroA.png" /><figcaption><em>One place to change the system. Different parts to build, test, and release.</em></figcaption></figure><p>Over roughly four years, I worked in a monorepo with six languages and around 20 to 30 services and components. There were backend services, plugins, web applications, and AI components. They shared a repository, but they did not all behave like the same kind of project.</p><p>The clearest benefit was integration.</p><p>When a model or DTO changed, it was easier to find the affected code and update it together. A DTO is the object used to carry data between parts of a system. Changing its shape can mean changing a producer, a consumer, tests, and sometimes a user interface.</p><p>Having those pieces in one place reduced the risk of overlooking an incompatible change. I could look at the whole change instead of reconstructing it across several repositories and pull requests.</p><p>I also remember waiting. Tests and hooks took time. Changes around base layers brought in tests far from the task I was working on. Commits arrived from unrelated parts of the repository. Keeping standards consistent needed attention, and changes to the release structure needed following.</p><p>Both sides belong in the story. I would want to keep the integration benefit. I would put more deliberate work into the daily cost of sharing the repository.</p><h3>Keep the cross-service change visible</h3><p>Consider a small example: a backend adds a field to a response, a plugin reads it, and a web application displays it.</p><p>In one repository, the pull request can show the producer, the consumers, and the tests together. A reviewer can follow the field from its definition to its use. If code generation is involved, the schema and generated clients can be checked as part of the same change.</p><p>That does not prove the feature works. It does make some missing pieces easier to notice. The plugin may still expect the old field name. A test fixture may use the wrong type. The web application may assume a value is always present.</p><p>This is the part of a monorepo I would protect. Moving everything apart just to make each directory quieter can introduce another cost: coordinating changes that used to be visible in one diff.</p><p>That visibility should help reviewers too. A contract change should explain which components produce it, which consume it, and which versions may coexist. A large pull request containing all the code still needs a readable explanation of the dependency between its parts.</p><p>The repository gives you a convenient place to inspect integration. The review process has to use it.</p><h3>“Unrelated to my task” is not always “unaffected”</h3><p>One frustrating part was seeing tests run in areas that seemed unrelated to the change I wanted to make.</p><p>There are two different problems hiding there.</p><p>A test may run because the pipeline selects too much work. It may also run because a shared base layer really does connect those areas. In the second case, skipping the test would hide the dependency without removing it.</p><p>Today, my first question would be why a target was selected. Which changed input led to this test? Was it a source dependency, a generated file, a compiler setting, or a global configuration change?</p><p>Pants documents the difference between checking changed files and including their dependents. Its CI guide uses transitive changed dependents for checks that need to account for downstream effects, and it calls out cases where configuration changes need broader validation. <a href="https://www.pantsbuild.org/stable/docs/using-pants/using-pants-in-ci">1</a></p><p>That is a useful principle even when the repository uses another build tool. Directory filters alone are a weak model of how software depends on other software.</p><p>In a repository with several build systems, the boundaries between their graphs need checking too. If a schema change feeds generated code in another language, that edge must exist somewhere the CI selection process understands. Each tool can be correct about its own targets while the overall pipeline still misses a consumer.</p><p>The goal would be a test selection I can explain and trust. On changes where the graph is incomplete or a shared toolchain changes, a broader run is reasonable.</p><h3>Give the base layer a smaller job</h3><p>A shared layer is attractive because another service already needs something similar. Over time, it can become a convenient home for things that have little in common.</p><p>Logging helpers arrive beside domain models. A small utility gains a dependency on a large client library. More services import the package because they need one function from it.</p><p>Then a small edit reaches further than expected.</p><p>I would review heavily shared packages by asking what their consumers actually need. Can stable protocol definitions stand on their own? Can a small utility avoid pulling in application-specific code? Does a domain rule belong with its owning service instead of the lowest common layer?</p><p>I would not split every helper into a separate package. That has its own maintenance cost. I would start with dependencies that repeatedly widen builds and tests, or make an otherwise local change difficult to release.</p><p>This is where the waiting becomes useful evidence. A slow CI job may be a tooling problem. It may also be showing you that the code has become more connected than the team intended.</p><p>Renaming a directory will not change that. Narrowing a real dependency can.</p><h3>Put short feedback close to the edit</h3><p>Long hooks were another recurring irritation. A commit is a small action in a developer’s day. Attaching too much work to it makes the cost appear again and again.</p><p>If I were setting the policy today, I would give local checks a clear purpose: catch cheap, obvious mistakes quickly. Formatting, basic linting, and selected fast checks fit that purpose. A broad integration suite usually needs another place to run.</p><p>The pre-commit framework supports file filters and hook stages, so hooks do not all need to run on every file at the same point in the workflow. Its configuration also supports pinned hook revisions. <a href="https://pre-commit.com/">2</a></p><p>The harder decision is what to put behind those settings. I would ask developers to run a small relevant test target while editing, keep commit-time work predictable, and let required CI checks enforce the wider policy before merging.</p><p>Local hooks are useful feedback, but they can be bypassed or missing. They should not be the only place a required check exists.</p><p>Waiting for a runner deserves its own measurement. To a developer, queue time and execution time are both time lost. Adding a cache does not help much if most of the wait happens before the build begins.</p><p>The measurement I would keep is time from a change to actionable feedback, including slower cases. A collection of impressive individual job times can still produce an unpleasant working day.</p><h3>Cache results only when the inputs are understood</h3><p>A shared build cache can remove repeated work across machines. In a repository this size, that is worth taking seriously.</p><p>It is also worth understanding what makes a result reusable.</p><p>Bazel’s remote cache works with build actions and their declared inputs and outputs. Its documentation warns about tools outside the workspace that are not tracked as inputs. A cache cannot account for a relevant dependency that the build description leaves out. <a href="https://bazel.build/remote/caching">3</a></p><p>Compiler and tool versions, generator inputs, environment dependencies, and lockfiles all deserve checking before a high cache-hit rate counts as success. A fast result is only useful if it belongs to the current inputs.</p><p>Clean and warm builds need separate measurements, with attention to the jobs that determine the overall completion time. Saving work on many small targets may barely change the time a developer waits for one long, uncached integration job.</p><p>This would also make cache failures easier to discuss. “The cache did not help this change” is more useful when we know whether the cause was changed inputs, missing entries, download time, or a job that could never reuse a result in the first place.</p><h3>Make Git easier to read and cheaper to use</h3><p>The repository had a steady flow of commits from parts of the system unrelated to my immediate work. Following that traffic made everyday Git work harder.</p><p>Some of that was an attention problem. The amount of data in a large repository raises a different set of questions.</p><p>For attention, path-limited history helps when investigating one area. For example, with illustrative directory names:</p><pre>git log --oneline -- services/payments/ packages/contracts/</pre><p>Git supports limiting history by paths. That gives me a more focused view; it does not create an independent branch history or remove dependencies outside those paths. <a href="https://git-scm.com/docs/git-log">4</a></p><p>For large checkouts, sparse checkout and partial clone address different costs. Sparse checkout limits the working-tree paths present locally. A partial clone using a filter such as blob:none can defer downloading file contents until needed, when supported by the server. Neither feature removes everyone else&#39;s commits from the repository&#39;s history. <a href="https://git-scm.com/docs/git-sparse-checkout">5</a> <a href="https://git-scm.com/docs/git-clone">6</a></p><p>I would test these with the actual build workflow before recommending them to the whole team. A convenient small checkout stops being convenient if code generation expects missing directories or a build immediately downloads everything anyway.</p><p>More commits also do not automatically mean more conflicts. Edits to independent files often merge cleanly. The difficult cases deserve attention of their own: shared configuration, lockfiles, generated outputs, and changes that cross the same interfaces.</p><h3>Share standards without forcing identical tooling</h3><p>Six languages need consistent expectations. They do not need the same formatter or the same test runner.</p><p>A small common set of requirements would be my starting point: an obvious build command, a test entry point, a named owner, dependency update rules, and a documented release path. Each language can meet those requirements with tools that suit it.</p><p>Shared configuration needs ownership too. A change to a root hook, base image, or code generator can affect people who never touch its directory. Someone should understand that reach and be responsible for reviewing changes to it.</p><p>CODEOWNERS can help route reviews. On GitHub, requiring approval from code owners is a separate branch protection setting; simply adding the file does not enforce that approval. <a href="https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners">7</a></p><p>I would prefer a few enforced expectations with clear owners over a long standards document that depends on everyone remembering to read it.</p><h3>One commit still has to survive several releases</h3><p>The biggest limit of the integration benefit appears after merging.</p><p>A backend service, a plugin, and a web application can be correct together in one commit and still reach their users at different times. A plugin may remain on an older version while the backend moves forward. A rollback can bring an older consumer back into use.</p><p>This is why I would make release compatibility part of the contract review.</p><p>Protocol Buffers gives concrete examples: adding fields can be safe for binary wire compatibility, while reusing field numbers is dangerous. It also distinguishes binary compatibility from source-level and application concerns. Successful parsing does not prove that two versions agree on meaning. <a href="https://protobuf.dev/programming-guides/proto3/#updating">8</a></p><p>For an illustrative change from timeout_seconds to timeout_ms, I would introduce the new field alongside the old one and define which value takes precedence. Readers would learn the new field while still accepting the old representation. Writers would keep supporting older consumers during the transition. Removal would wait until the supported version combinations no longer need the old field.</p><p>Those tests need rollback combinations too. Testing only the newest producer with the newest consumer misses the period when releases overlap.</p><p>Release records should make that overlap visible: which artifact was deployed, which commit produced it, and which contract versions it supports. If the release process changes, that information should remain easy to find.</p><p>Sharing a Git repository is a weak reason to release every component together. When two components depend on being released in a particular order, that dependency needs to be explicit.</p><h3>What I would keep</h3><p>I would keep the ability to follow an integration change across the system in one place. It helped when models and DTOs changed, and it reduced the chance of leaving a consumer behind.</p><p>I would spend more effort on the costs that arrive every day: broad test selection, heavy base layers, long hooks, noisy history, and release tracking. Those are easy to postpone because each one looks manageable on its own.</p><p>Together, they shape how pleasant the repository is to work in.</p><p>The question I would bring to the next monorepo is simple: when one small thing changes, how much of the system should a developer have to think about?</p><p>I want the rest to remain available when I need it. I don’t want every edit to require understanding all of it.</p><h3>Sources</h3><ol><li><a href="https://www.pantsbuild.org/stable/docs/using-pants/using-pants-in-ci">Pants: Using Pants in CI</a>.</li><li><a href="https://pre-commit.com/">pre-commit: Configuration, file filtering, and hook stages</a>.</li><li><a href="https://bazel.build/remote/caching">Bazel: Remote Caching</a>.</li><li><a href="https://git-scm.com/docs/git-log">Git: git-log</a>.</li><li><a href="https://git-scm.com/docs/git-sparse-checkout">Git: git-sparse-checkout</a>.</li><li><a href="https://git-scm.com/docs/git-clone">Git: git-clone, including partial-clone filters</a>.</li><li><a href="https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners">GitHub: About code owners</a>.</li><li><a href="https://protobuf.dev/programming-guides/proto3/#updating">Protocol Buffers: Updating a proto3 message type</a>.</li></ol><p><em>I’m Burak Hamuryen, a software engineer in Berlin working on distributed systems and real-time video infrastructure. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=004795fac1a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before Buying More GPUs, Fix Your Video Pipeline]]></title>
            <link>https://medium.com/@hamuryen/before-buying-more-gpus-fix-your-video-pipeline-59aefd3c85dd?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/59aefd3c85dd</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[streaming-video]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 13:01:03 GMT</pubDate>
            <atom:updated>2026-09-15T13:01:03.878Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The expensive part may be getting frames to the GPU, keeping them there, and moving them out on time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7nd8ByspquMAzl7KO6YHg.png" /><figcaption><em>A faster GPU cannot remove a queue somewhere else in the pipeline.</em></figcaption></figure><p>Take a video service that starts falling behind as more streams arrive. Playback gets later. Memory usage climbs. Someone opens a capacity request for another GPU machine.</p><p>That might be the right purchase. I would still want to follow one frame through the service before approving it.</p><p>Where does it wait? Which thread moves it forward? How many times does it cross between CPU and GPU memory? What happens when the destination cannot accept it?</p><p>I’ve worked on native video systems and RTSP-to-WebRTC bridges. That background makes me interested in the gaps between the named components. A diagram can say “hardware decode” and “hardware encode” while leaving out a download, a CPU filter, an upload, and a blocking write between them.</p><p>Those gaps deserve a place in the capacity discussion.</p><h3>Start with the video you actually need</h3><p>Before measuring a pipeline, write down its output requirements.</p><p>A live preview needs recent frames. A recording needs a clear policy for preserving video and reporting gaps. An offline export might mainly need to finish quickly. These jobs can share code, but their definitions of success are different.</p><p>For a live service, specify the expected resolution, frame rate, codec, and acceptable delay. Decide what can happen under overload too. Can the preview skip frames? Can the source lower its bitrate? When must the service reject another stream?</p><p>Without those decisions, “supports more streams” is an incomplete result. A service that accepts every connection but delivers video several seconds late may already be over capacity.</p><p>Then ask whether the job needs decoded frames at all.</p><p>FFmpeg’s stream-copy path transfers encoded packets without decoding and encoding them again. When the destination accepts the existing codec and stream parameters, remuxing into a suitable container can avoid that work. It does not support filters that need decoded frames, and container compatibility still matters. <a href="https://ffmpeg.org/ffmpeg.html#Streamcopy">1</a></p><p>A recording or relay path is worth checking here. Decoding video just to encode the same thing again should be a deliberate choice. Perhaps the output needs another codec, resolution, or bitrate. Perhaps it doesn’t.</p><h3>Draw the memory path</h3><p>A useful pipeline sketch shows more than component names:</p><pre>encoded packets<br>    -&gt; hardware decoder<br>    -&gt; decoded frames in GPU memory<br>    -&gt; resize or format conversion, if needed<br>    -&gt; hardware encoder<br>    -&gt; encoded packets<br>    -&gt; network or storage</pre><p>Now mark every place a frame leaves GPU memory. Also mark where the code waits for another operation to finish.</p><p>In NVIDIA’s FFmpeg guide, -hwaccel cuda -hwaccel_output_format cuda selects a hardware decode path with frames kept in GPU memory. Compatible GPU filters and hardware encoding can then continue that path. A CPU filter inserted between those stages may require a download and a later upload. Check the complete filter chain and the capabilities of your installed build. <a href="https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/ffmpeg-with-nvidia-gpu/index.html">2</a></p><p>The raw data adds up quickly. NV12 stores 8-bit YUV 4:2:0 video at 12 bits per pixel, or 1.5 bytes per pixel before padding. <a href="https://learn.microsoft.com/en-us/windows/win32/medfound/recommended-8-bit-yuv-formats-for-video-rendering">3</a> For a tightly packed 1920 × 1080 frame, the payload calculation is:</p><pre>1920 × 1080 × 1.5 = 3,110,400 bytes per frame<br>3,110,400 × 30 = 93.312 MB per second</pre><p>Here, MB means one million bytes. At 30 frames per second, downloading every frame and uploading it again moves about 186.6 MB per second of raw payload per stream. Forty streams would move about 7.46 GB per second across those two directions combined.</p><p>That is arithmetic, not a benchmark. It excludes row padding, alignment, other copies, and transfer overhead. It also does not mean 7.46 GB per second travels in each direction, or that every machine will hit a bus limit at that rate.</p><p>It gives you something specific to investigate: a small CPU operation between two GPU stages can require moving a surprisingly large amount of data.</p><p>When reading native code, I would look for the reason behind each copy. Does the consumer need its own buffer? Is the format incompatible? Did a convenient library API quietly force the data through host memory? Some copies will be necessary. Others may be leftovers from an earlier design.</p><h3>Check which part of the GPU is busy</h3><p>“GPU utilization is low” needs a second question: which utilization?</p><p>NVIDIA’s monitoring tools distinguish general GPU activity from encoder and decoder activity. The nvidia-smi documentation also distinguishes memory utilization from the amount of allocated framebuffer memory. Metric support varies by device and configuration; an unavailable reading is not evidence that an engine is idle. <a href="https://docs.nvidia.com/deploy/nvidia-smi/index.html">4</a></p><p>A video workload can put pressure on dedicated codec hardware while leaving much of the general compute capacity available. A low general GPU percentage therefore does not establish spare decoding or encoding capacity.</p><p>Collect those readings alongside CPU usage, input and output rates, transfer activity, and queue age. They need to cover the same interval. Comparing yesterday’s average GPU graph with today’s worst stream tells you very little.</p><p>The useful observation is a relationship. Perhaps output slows while encoder activity stays high. Perhaps every engine looks quiet while one CPU thread is busy. Perhaps output only falls behind when the storage destination slows down.</p><p>Each observation points to a different next measurement. None is a diagnosis by itself.</p><p>It is also worth looking at individual streams. An average can hide one expensive input format, one unstable source, or a few sessions that retain buffers much longer than the others. A fleet total is helpful for capacity planning; a per-stream timeline helps explain where that capacity went.</p><h3>A frame can be waiting for its own buffer</h3><p>Memory usage does not have to grow forever for buffer ownership to hurt throughput. A fixed pool can run out of available surfaces because downstream work is still holding them.</p><p>NVIDIA’s NVDEC guide makes two details explicit. cuvidMapVideoFrame() waits for decoding to complete. Calling it on the thread that submits decode work can prevent that thread from submitting more work while it waits. Mapped output surfaces must also be released with cuvidUnmapVideoFrame(); only a limited number may remain mapped. <a href="https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvdec-video-decoder-api-prog-guide/index.html">5</a></p><p>For code using that API, inspect the lifetime of a surface from acquisition to release. A reference held by an encoder, a queue, or an error path can matter just as much as the allocation itself.</p><p>Returning a surface too early is not a performance fix. If asynchronous work still reads it, reuse can corrupt the result. The release point has to follow the actual completion of the last consumer.</p><p>This is one reason I like ownership to be visible in the code. A frame handle should make it possible to answer who currently owns the data and what event makes it reusable. A raw pointer passed through several callbacks makes that question harder.</p><p>Adding another worker thread can help when submission is blocked. It can also add more outstanding work to the same exhausted pool. I would measure the wait and understand the lifetime before increasing concurrency.</p><h3>Bigger queues can make a live service worse</h3><p>Suppose a source produces 30 frames per second and a downstream stage can sustain only 25. An unbounded queue gains five frames every second. A larger queue delays the moment when the system must deal with that mismatch.</p><p>It also lets the video get older.</p><p>For a live preview, I care about how long the oldest frame has been waiting. A queue with ten frames has a different meaning at 5 fps and 60 fps. Count and byte limits protect resources; an age limit expresses something closer to the viewing requirement.</p><p>GStreamer’s queue element supports limits and can either block or discard buffers when full, depending on its configuration. These are different overload policies, with different consequences. <a href="https://gstreamer.freedesktop.org/documentation/coreelements/queue.html">6</a></p><p>Choose the policy at the right stage. Dropping an old decoded frame before presentation may be acceptable for a live preview. Arbitrarily dropping compressed data can damage later frames that depend on it. A recording branch needs its own decision about gaps, buffering, and failure reporting.</p><p>Give the viewer and recording writer separate branches with finite budgets. Separate threads alone do not provide lasting isolation if both branches eventually block on shared buffers or shared output work.</p><p>When a budget is exhausted, make the result observable. Count intentional drops. Report recording gaps. Reject work if necessary. A service that silently accumulates delay is difficult to operate because its failure arrives long after its capacity was exceeded.</p><h3>The recent SDK work is worth reading</h3><p>NVIDIA’s July 31, 2026 article about Video Codec SDK 13.1 describes updated transcoding samples with separate submission work and queues between stages. It also introduces AppTransZeroCopy, which can share suitable CUDA arrays between decode and encode instead of using an intermediate copy and conversion. <a href="https://developer.nvidia.com/blog/nvidia-video-codec-sdk-13-1-zero-copy-transcode-av1-b-frames-and-frame-accurate-seek/">7</a></p><p>The interesting part is the treatment of memory ownership and scheduling as part of video performance. These are concrete examples to study when inspecting a similar path in your own application.</p><p>The sample’s benefits depend on a compatible path, including hardware, driver, format, and processing requirements. “Zero copy” in one handoff does not mean that an entire application moves no data. Nor does installing a newer SDK automatically reorganize an existing pipeline.</p><p>I would use the sample to form a specific hypothesis: perhaps this intermediate surface or synchronization point is avoidable. Then I would check that hypothesis against the application’s actual output requirements.</p><h3>Measure a change you can explain</h3><p>Start with a repeatable workload and keep a small record of the test conditions: GPU model, driver, FFmpeg or SDK version, codecs, resolution, frame rate, encoder settings, and destination.</p><p>The input needs to match the question. Reading a local file as quickly as possible can help measure processing capacity. It does not reproduce a live source’s pacing, reconnects, or network variation. I would use both kinds of test when the service has to handle both conditions.</p><p>Record four things together:</p><ul><li>Useful output: completed frames or playable output at the required settings.</li><li>Delay: time spent inside measured stages and queues, including the slower cases.</li><li>Resource use: CPU, relevant GPU engines, memory, transfers, and output I/O.</li><li>Failure behavior: drops, errors, reconnects, and recovery after overload.</li></ul><p>Local timing should use a monotonic clock. Capture-to-display delay is a separate measurement and needs a trustworthy relationship between the source and destination clocks.</p><p>Change one part of the path. Remove an unnecessary host round trip, shorten a surface lifetime, or isolate a slow output. Repeat the same workload and check output correctness as well as speed.</p><p>For diagnosis, a temporary discard sink can show whether a real output destination is holding things up. The final capacity test still needs that destination. Otherwise, the result leaves out work the deployed service must do.</p><p>Let the test run long enough to expose a growing backlog. A short burst can look healthy while its queues borrow time from the rest of the system. Recovery matters too: after input load falls, does latency return to normal, or does the service keep showing old video?</p><p>Only then would I increase stream count and look for the first requirement the service can no longer meet.</p><h3>Make the hardware request specific</h3><p>Sometimes the result will be clear: the required codec engine is saturated, memory capacity is insufficient, or the application needs more independent processing capacity. More hardware may be exactly the right answer.</p><p>The investigation is still useful. It tells you which resource to buy and what additional capacity to expect under the tested conditions.</p><p>Other times, a GPU spends part of its day waiting for frames, a free surface, or an output writer. Another GPU might leave those waits untouched.</p><p>Before buying it, follow one frame. Find out where its time goes.</p><h3>Sources</h3><ol><li><a href="https://ffmpeg.org/ffmpeg.html#Streamcopy">FFmpeg: Streamcopy</a>.</li><li><a href="https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/ffmpeg-with-nvidia-gpu/index.html">NVIDIA: Using FFmpeg with NVIDIA GPU Hardware Acceleration, SDK 13.0</a>.</li><li><a href="https://learn.microsoft.com/en-us/windows/win32/medfound/recommended-8-bit-yuv-formats-for-video-rendering">Microsoft: Recommended 8-Bit YUV Formats for Video Rendering</a>.</li><li><a href="https://docs.nvidia.com/deploy/nvidia-smi/index.html">NVIDIA: NVIDIA System Management Interface documentation</a>.</li><li><a href="https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvdec-video-decoder-api-prog-guide/index.html">NVIDIA: NVDEC Video Decoder API Programming Guide, SDK 13.0</a>.</li><li><a href="https://gstreamer.freedesktop.org/documentation/coreelements/queue.html">GStreamer: queue</a>.</li><li><a href="https://developer.nvidia.com/blog/nvidia-video-codec-sdk-13-1-zero-copy-transcode-av1-b-frames-and-frame-accurate-seek/">NVIDIA: Video Codec SDK 13.1 — Zero-Copy Transcode, AV1 B-Frames, and Frame-Accurate Seek</a>, July 31, 2026.</li></ol><p><em>I’m Burak Hamuryen, a software engineer in Berlin working on distributed systems and real-time video infrastructure. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59aefd3c85dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents Are Distributed Systems. Treat Them Like One.]]></title>
            <link>https://medium.com/@hamuryen/ai-agents-are-distributed-systems-treat-them-like-one-c4fcd0455708?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4fcd0455708</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 21:21:30 GMT</pubDate>
            <atom:updated>2026-09-13T21:21:30.809Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What happens when a tool succeeds, the response gets lost, and your agent tries again?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66QqHhTSKGtpdK9ia_2SUQ.png" /><figcaption>The action succeeded. The response never arrived. What should the agent do next?</figcaption></figure><p>Imagine a support agent handling a refund.</p><p>It reads the ticket, checks the order, and calls the refund API. The payment service records the refund. Then the connection drops before the response gets back.</p><p>The agent sees a timeout. Retrying sounds reasonable, but the first refund may already be on its way. A second request could issue another one. Asking the model to think harder won’t tell you whether the payment service committed the transaction.</p><p>This is the part of building agents that interests me. I’ve spent much of my career working on backend services, video pipelines, and infrastructure. When I look at an agent calling several tools to finish a task, I recognize a lot of the same problems.</p><p>Once an agent calls remote tools and changes data in other services, its work spans several systems. Something can succeed in one place and fail in another. A process can die halfway through the job.</p><p>Adding a model gives that system a new way to choose its next step. The old failure modes are still there.</p><h3>The timeout tells you less than you think</h3><p>After a timeout, several things could have happened. The request never reached the service. The service rejected it. The refund succeeded, but the response was lost. The service might even still be processing it.</p><p>From the caller’s side, these can look exactly the same.</p><p>The refund operation needs an idempotency key: a stable ID for this particular action. Every retry sends the same key. The receiving service uses it to recognize repeat requests and avoid issuing another refund.</p><p>The important word is <em>stable</em>. If your tool wrapper creates a new UUID every time it runs, every retry looks like a new refund.</p><p>Application code should create and save that key before making the first request. It belongs to the business operation, with its customer, order, amount, and currency. Reusing it with different details should fail.</p><p>For example, the job might save an operation ID of refund-op-7842. All three attempts use refund-op-7842. Even if the model proposes the refund again in different words, the application must recognize the existing operation. A fresh tool call doesn&#39;t automatically mean a new business action.</p><p>AWS explains this contract in <a href="https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/">Making retries safe with idempotent APIs</a>. Check the provider’s retention rules too. <a href="https://docs.stripe.com/api/idempotent_requests">Stripe, for example, allows keys to be removed after at least 24 hours</a>. An old job can’t assume that its key still protects it.</p><p>There is a catch: saving a key in your own database isn’t enough when the action happens somewhere else. Your worker can still crash after the external service succeeds and before you save its response.</p><p>The service performing the action needs to support deduplication, or give you a reliable way to look up what happened. An empty search result isn’t proof of failure if the first request might still be running. Some jobs need to stop for investigation. An unknown outcome is a valid state. Pretending it means “failed” can get expensive.</p><h3>A chat history is a poor job database</h3><p>Suppose the agent’s conversation contains this line:</p><blockquote><em>I have processed the refund and will now notify the customer.</em></blockquote><p>That tells you what the model said. Before showing the customer a success message, I want a receipt from the payment service.</p><p>For a job like this, I would store the proposed action, its validated inputs, the approval if one was needed, the operation ID, and the confirmed external result. The conversation can help explain the decision. The job record tells the application what it can safely do next.</p><p>This also changes how you handle a restart. A replacement worker should be able to load the job and see that the refund is confirmed but the notification is still pending. It shouldn’t have to reread a conversation and guess.</p><p>I’d keep the state names plain: proposed, approved, running, confirmed, outcome unknown, failed. Moving a refund to “confirmed” requires evidence from the payment service. A confident sentence from the model doesn’t qualify.</p><h3>Put a boundary around the model’s decision</h3><p>The model is useful when a request needs interpretation. A customer writes three paragraphs about a damaged item, and the agent works out which order they mean and what help they want.</p><p>Once it proposes a refund, regular application code can take over much of the work.</p><p>Does this order belong to the customer? Is the amount valid? Has it already been refunded? Does the current user have permission? Is approval required?</p><p>These checks belong at the tool boundary, where they run regardless of what the prompt says.</p><p>The flow I would start with looks like this:</p><pre>Read the request<br>    -&gt; Ask the model for a proposed action<br>    -&gt; Validate the action in code<br>    -&gt; Save the proposal and operation ID<br>    -&gt; Get approval when required<br>    -&gt; Execute through a controlled tool<br>    -&gt; Record the confirmed result<br>    -&gt; Tell the customer what happened</pre><p>This leaves the model room to handle messy language without giving it ownership of every business rule.</p><p>It also makes failure easier to explain. “The amount exceeds the allowed refund” is something you can test and show to a user. A long conversation where the model talks itself into a different amount is much harder to reason about.</p><h3>Where Temporal fits</h3><p>Long-running video jobs have a similar shape. A request may pass through export, processing, storage, and notification. Some steps take time. Some fail. Restarting the entire chain can repeat expensive work.</p><p>That is the kind of problem where a workflow system becomes useful.</p><p>With Temporal, I would keep the coordination in a Workflow and put model calls and external API calls in Activities. Temporal records execution history so workers can rebuild workflow state after a failure. The <a href="https://docs.temporal.io/workflow-definition">workflow code must be deterministic</a>: replaying the same recorded history must produce the same sequence of commands.</p><p>The distinction matters for agents. A fresh model call can produce a different answer. During recovery, a recorded Activity result lets the workflow reuse the earlier decision. An Activity whose completion wasn’t recorded may still run again, so the uncertainty hasn’t disappeared.</p><p>Temporal also doesn’t make a refund API safe to retry. If the payment succeeds and the Activity worker dies before reporting completion, another attempt can call that API again. The <a href="https://docs.temporal.io/activity-execution">Activity execution documentation</a> covers this retry behavior. The operation ID still needs to travel all the way to the service that performs the refund.</p><p>I wouldn’t add Temporal to every agent project. For a short task with a few steps, a database job table and a worker may be enough. You still have to design job claiming, retries, and recovery, but that can be a reasonable amount of code.</p><p>Once jobs wait for people, span several services, or need careful recovery across many steps, I’d look much more closely at a workflow engine.</p><h3>Human approval becomes stale</h3><p>“Ask a human first” sounds like a complete solution until the human takes two days to answer.</p><p>During those two days, someone else might refund the order. The customer’s request might change. The person who started the job might lose access.</p><p>A saved approval should refer to a specific action: this order, this amount, this currency, this version of the proposal. If the proposal changes, the old approval should no longer apply.</p><p>Before execution, the system should check current permissions and business conditions again. Those checks also need protection against concurrent changes at the service performing the action. A check in the agent process alone leaves a gap between checking and doing.</p><p>I would give approvals an expiry time too. Otherwise, an old job can wake up weeks later and perform something nobody is expecting anymore.</p><p>The interface should show what is waiting, who needs to respond, and what will happen after approval. “Agent is thinking” is a bad description of a job that has been waiting for a manager since Tuesday.</p><h3>Give retries an owner and a budget</h3><p>An agent can retry at several levels without anyone intending it.</p><p>The HTTP client retries. The tool wrapper retries. The workflow retries the Activity. Then the model sees an error and decides to try the tool again.</p><p>If three layers each make three attempts, one logical action can turn into 27 downstream calls. During an outage, that extra load makes recovery harder.</p><p>I’d choose where retry policy lives and keep the other layers visible. Temporary failures can use bounded retries with increasing delays and jitter. Invalid input and permission failures should usually go back for correction. An uncertain write needs reconciliation before another attempt unless the receiving API can safely deduplicate it.</p><p>The agent also needs limits on the whole job: tool calls, elapsed time, model spend, and repeated attempts at the same action. AWS covers the service-side reasoning in its guidance on <a href="https://docs.aws.amazon.com/wellarchitected/latest/framework/rel_mitigate_interaction_failure_limit_retries.html">controlling retry calls</a>.</p><p>The exact limits depend on the task. The application should enforce them outside the model. A prompt saying “don’t spend too much” is hard to put on a dashboard.</p><h3>Debug the job from its receipts</h3><p>When a customer asks why they received two notifications, the final assistant message won’t be enough.</p><p>I want to follow one job ID through the proposal, tool attempts, external requests, and results. Each attempt should have its own ID, while retries of the same business action keep the same operation ID.</p><p>Record the model and prompt version as well. They help explain why an action was proposed. Keep sensitive content out of general logs; store only what you need with appropriate access and retention.</p><p>Then measure the outcome of the job. Did the requested task finish? How long did it take? How many jobs are stuck waiting? How many have an unknown external outcome? How much did each completed task cost?</p><p>A successful model response is only one event in that chain. The payment receipt and the delivery status tell you whether the customer actually got what they asked for.</p><p>Adding more agents makes those IDs even more useful. If two agents pick up the same ticket, they need a shared way to recognize work already in progress. I’d start with one agent and add another when a specific part of the job benefits from it.</p><h3>The test I’d run before shipping</h3><p>Take the refund flow and make the payment service return success. Kill the worker immediately afterward, before it saves the result.</p><p>Restart it.</p><p>Does it issue another refund? Does it find the first one? Does it stop with an unknown outcome? Can you tell which happened without reading every log line?</p><p>That one test exercises a boundary that a happy-path demo never touches.</p><p>I would also run the same job on two workers, deliver the same approval twice, and change the order while approval is pending. Then make a tool time out repeatedly and check that the job eventually stops within its budget.</p><p>You can run most of these with a fake model returning a fixed proposal. That makes the recovery behavior easier to test. Separately, test the model’s decisions against examples of ambiguous requests, missing information, and actions it shouldn’t propose.</p><p>Both kinds of tests matter. A system can reliably execute the wrong decision. It can also make the right decision and lose track of the result.</p><p>Before shipping, I want an answer to this question: if the process dies after an external action, what will the next worker do?</p><p>For our refund, it loads the saved operation ID, checks the payment service, finds the existing receipt, and continues with the notification. If it can’t establish what happened, it leaves the refund alone and flags the job for review.</p><p>Once that works, I’d feel much better about letting the agent handle the next ticket.</p><p><em>I’m Burak Hamuryen, a software engineer in Berlin working on distributed systems, real-time video processing, and AI infrastructure. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4fcd0455708" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Monolith to 15 Microservices: When It Actually Made Sense]]></title>
            <link>https://medium.com/@hamuryen/from-monolith-to-15-microservices-when-it-actually-made-sense-e57c161b62b7?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/e57c161b62b7</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[soap]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 05:16:01 GMT</pubDate>
            <atom:updated>2026-04-23T05:16:01.528Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Everyone’s writing about going back to monoliths. Here’s why we went the other way in 2013, before “microservices” was even a word we knew.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsRmcsEo4GHVYcSV5UdHcQ.png" /><figcaption>Three engineers, fifteen services, zero containers. Sometimes less infrastructure is the answer.</figcaption></figure><p>In May 2011, a group of software architects met at a workshop near Venice and started describing something they called “micro services.” By May 2012, they settled on the name “microservices.” <a href="https://martinfowler.com/articles/microservices.html">Martin Fowler and James Lewis published the article</a> that made the term mainstream in March 2014.</p><p>I didn’t read any of that. In late 2013, I was an engineer at a small defense and video analytics company going through a transition. Most of the senior engineers had left. I was mid-level with about a year of experience, but I was the most experienced developer on the team. I split a C++ application into 15 separate services because the monolithic version we’d built the year before was getting in the way.</p><p>Same idea. Different continent. No buzzwords.</p><h3>The Monolith We’d Already Built</h3><p>The year before, we’d built a video management system for a client. C++, Qt for the desktop frontend, PostgreSQL for the database, gSOAP for the service layer. Standard stack for the era. It was a monolith: one codebase, one build, one deployment.</p><p>It worked fine for a single client. But when we decided to build our own product, a VMS we’d sell to multiple customers and deploy on-premise at their sites, the monolith’s limits became obvious. Every change to the camera integration module required rebuilding and redeploying the entire system. Authentication code that hadn’t changed in months got retested because it shared a binary with alerting code that changed weekly. Different features had completely different update cycles, but they were all locked together.</p><p>So for the new product, I designed it differently. Not because I’d read about microservices. Because I’d experienced the monolith, and I didn’t want to do it again.</p><h3>Splitting It Up</h3><p>I broke the system into about 10–15 separate services. Each one was its own C++ project, its own binary, its own process:</p><ul><li><strong>User service</strong>: authentication, login, permissions, roles</li><li><strong>Camera/asset service</strong>: device management, stream configuration, brand-specific integrations</li><li><strong>Recording service</strong>: storage management, retention policies, playback</li><li><strong>Live view service</strong>: real-time stream distribution to clients</li><li><strong>Alerting service</strong>: rule engine, event triggers, notifications</li><li><strong>Analytics service</strong>: video analytics processing, detection events</li><li>And several more for logging, configuration, licensing</li></ul><p>Each service had its own PostgreSQL schema within a shared database instance. The user service owned the users schema, camera management owned assets, alerting owned alerts. They didn&#39;t reach into each other&#39;s tables. We couldn&#39;t afford to run 15 separate database instances for a product that would be deployed on whatever hardware the customer had on-premise, but the schema separation meant services stayed out of each other&#39;s data.</p><p>I built the architecture and the foundation. Then two developers joined: one junior, one with about a year of experience. Three people, 15 services.</p><h3>Why We Used SOAP Instead of REST in 2013</h3><p>If you’ve only ever worked with REST and JSON, brace yourself.</p><p>In 2013, SOAP was still the enterprise standard. REST was gaining ground, especially in the web world, but in C++ desktop applications talking to backend services, SOAP with gSOAP was the established tool. REST frameworks for C++ were immature or nonexistent. gSOAP gave us code generation from WSDL definitions, type-safe communication, and a protocol that worked.</p><p>It also gave us headaches.</p><p>gSOAP generates C++ code from your service definitions. You define the interface, run the generator, and get a pile of .cpp and .h files with XML serialization for every data type. For a single service calling a single other service, it works fine. Clean, structured, predictable.</p><p>The problem starts when one service needs to call multiple other services. The alerting service needed to talk to both the user service (to check permissions) and the camera service (to get device info). That meant including generated code from both services in the same project. And that’s where gSOAP broke down.</p><p>Namespace collisions. The generated code from the user service defined types and serialization functions that clashed with the generated code from the camera service. The solution was wrapping each client in its own C++ namespace, carefully isolating the generated files, and making sure nothing leaked across boundaries. It was tedious, fragile, and error-prone. Add a field to one service’s API and you’d spend an afternoon fixing compile errors in a consuming service that didn’t change at all. This was a <a href="https://gsoap.yahoogroups.narkive.com/A1fju6wM/problem-with-c-namespaces-using-the-generated-files">well-documented pain point</a> in the gSOAP community.</p><p>And then there was the XML overhead. Every call serialized data to XML, sent it over the wire, and deserialized on the other side. For the kind of data we were passing (device lists, user permissions, alert configurations), the XML payload was often 5–10x larger than the actual data. Not a disaster on a local network, but wasteful.</p><p>If I were doing it today, I’d use REST with JSON, or gRPC for the performance-sensitive paths. In 2013, those weren’t real options for C++. gSOAP was what we had, and it worked. Just not gracefully.</p><h3>No Docker, No Kubernetes, No Problem</h3><p>Each service ran as a Linux service on CentOS. Start, stop, restart independently. Check logs in /var/log/. That&#39;s it.</p><p>No containers. Docker had just released version 0.9 in 2013 and nobody in our world had heard of it. Kubernetes didn’t exist yet (Google released it in 2014). We didn’t have service discovery, load balancing, or health checks. Services found each other through configuration files that listed IP addresses and ports.</p><p>Deployment meant updating one binary on the customer’s server and restarting that one systemd service. When we needed to update the alerting service, we updated the alerting service. The camera service kept running. The user service kept running. No coordinated restart, no deployment pipeline, no downtime.</p><p>For on-premise deployments to customers who didn’t have cloud infrastructure (cloud wasn’t really an option for most of our customers in 2013), this simplicity was the whole point. The product ran on whatever server the customer had. Sometimes powerful, sometimes not. It had to be light.</p><h3>What We Got Wrong</h3><p><strong>No centralized logging.</strong> Each service logged to its own file. When a problem spanned multiple services, we’d open 4–5 terminal windows, tail different log files, and try to match timestamps by eye. A correlation ID flowing through all services would have saved us hours. We didn’t implement one because we didn’t know it was a pattern.</p><p><strong>No service discovery.</strong> Hardcoded IPs and ports in config files. Fine for a few deployments, painful for dozens. Every new customer site meant manually editing configuration.</p><p><strong>gSOAP for everything.</strong> We used it because we knew it, not because it was the best fit. The namespace collisions, the XML overhead, the code generation friction. A lighter protocol would have been better, but the C++ ecosystem in 2013 didn’t offer many alternatives.</p><p><strong>No health checks or circuit breakers.</strong> If the user service went down, the alerting service would keep trying to call it and eventually time out. No graceful degradation, no automatic recovery detection. We handled it with manual monitoring and restarts.</p><h3>Why It Worked Anyway</h3><p>Three people, 15 services, SOAP over gSOAP, CentOS, no containers, no orchestration, manual on-premise deployments. Sounds like it shouldn’t work. But it did, for years. Here’s why:</p><p><strong>The boundaries were obvious.</strong> Cameras are not users. Users are not alerts. Alerts are not recordings. We didn’t need Domain-Driven Design workshops to figure this out. The previous monolithic project had already shown us where the natural seams were. We just made them explicit.</p><p><strong>The team was small enough.</strong> Three people sitting next to each other. Communication overhead was zero. We didn’t need API contract management or service catalogs. We talked across the desk.</p><p><strong>The number was right.</strong> 10–15 services, not 60, not 200. Everyone could hold the full system in their head. Every person could debug every service. There was no “that’s the other team’s service” problem because there was no other team.</p><p><strong>On-premise forced simplicity.</strong> No cloud auto-scaling, no managed databases, no infinite compute. The product had to run on real hardware at real customer sites. This constraint killed over-engineering before it started. If it couldn’t run on a single server, it was too complex.</p><h3>What I Realized Later</h3><p>When Docker and Kubernetes exploded in 2017–2018 and “microservice architecture” became the thing everyone was talking about, I realized we’d been doing it for years. Different tools, same principles: independent deployment, domain-based separation, separate data ownership, process isolation.</p><p>The 2018 version came with an ecosystem we didn’t have: containerization, orchestration, distributed tracing, service meshes, circuit breakers. Tools that solve real problems. But tools that also add real complexity. We shipped a working product without any of them.</p><p>I’ve since worked on much larger systems with many more services, Kubernetes, Kafka, the full modern stack. The honest comparison: 15 well-bounded services with simple communication was easier to operate than larger architectures with sophisticated tooling. More services doesn’t mean better architecture. It usually means more things that can break.</p><h3>When Splitting Actually Makes Sense</h3><p>From doing this more than once:</p><p><strong>When you’ve already built the monolith.</strong> We built the monolithic version first. It taught us where the real boundaries were. When we built the product, we already knew which modules belonged together and which didn’t. Starting with microservices on day one is guessing. Starting after you’ve seen the domain is informed.</p><p><strong>When modules have different lifecycles.</strong> Our camera integration changed every week as we added new brands. Authentication changed once a quarter. Forcing them into the same build and deployment cycle was the actual problem.</p><p><strong>When the domain boundaries are obvious.</strong> If you have to argue about where to draw the line, maybe the line doesn’t exist yet. Our boundaries were clear because cameras, users, alerts, and recordings are genuinely different things with different data and different logic.</p><p><strong>When you can keep the number small.</strong> 10–15 services for 3 engineers worked. Each person understood every service. The moment you have services that nobody fully understands, you’ve gone too far.</p><p>If none of these apply to you, I wrote another post about why you probably don’t need microservices at all. (Link coming when both posts are published.)</p><h3>Further Reading</h3><ul><li><a href="https://martinfowler.com/articles/microservices.html">Martin Fowler &amp; James Lewis: Microservices (2014)</a></li><li><a href="https://martinfowler.com/bliki/MonolithFirst.html">Martin Fowler: MonolithFirst</a></li><li><a href="https://gsoap.yahoogroups.narkive.com/A1fju6wM/problem-with-c-namespaces-using-the-generated-files">gSOAP C++ Namespace Issues (Community Thread)</a></li><li><a href="https://samnewman.io/books/building-microservices/">Sam Newman: Building Microservices (O’Reilly)</a></li></ul><p><em>I’m Burak Hamuryen, a Senior Software Engineer in Berlin with 14+ years of experience building distributed systems, real-time video processing, and cloud-native platforms. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e57c161b62b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Mined Bitcoin in 2012 on an NVIDIA Tesla GPU. Then a Hard Drive Died.]]></title>
            <link>https://medium.com/@hamuryen/i-mined-bitcoin-in-2012-on-an-nvidia-tesla-gpu-then-a-hard-drive-died-a2b6163bd521?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2b6163bd521</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[personal-story]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 05:16:01 GMT</pubDate>
            <atom:updated>2026-04-21T05:16:01.235Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The most expensive hard drive I never bought was the one I bought instead of Bitcoin.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1HKRsTG_pbWVuLc_JidqA.png" /><figcaption>A GPU that survived, a hard drive that didn’t, and 0.7 Bitcoin somewhere in between.</figcaption></figure><p>It was late 2012. I’d just started my first real engineering job. I was 22, excited about everything, and sitting in front of a Dell workstation with an NVIDIA Tesla GPU jammed inside it. The card was the size of a small country. No display output, no fan shroud, just raw compute. We used it for CUDA programming: face recognition, license plate detection, video analytics. Serious work. The kind of work where you compile something and go make tea.</p><p>One afternoon, a coworker walked up to my desk.</p><p>“Have you heard of Bitcoin?”</p><p>I had not.</p><p>He explained it to me like I was five, which was appropriate because my understanding of economics was roughly at that level. There’s a program. You run it on your computer. It does math. The math earns you money. The money shows up on a website.</p><p>“How much money?”</p><p>“Bitcoin is around 11 dollars right now.”</p><p>Eleven dollars. A movie ticket. A mediocre lunch. For doing math. On a computer I already had.</p><h3>The Experiment</h3><p>We installed whatever mining software was popular at the time (I honestly cannot remember the name). Pointed it at the Tesla card. Hit start. The same GPU that spent its weekdays detecting faces in surveillance footage and reading license plates from blurry traffic cameras was now doing math for strangers on the internet. The workstation started humming in a way that made the facilities guy look over from his desk.</p><p>After a day or two, we checked the mining pool website. About 4 or 5 dollars had accumulated. We looked at each other with the grin of two guys who had just discovered free money.</p><p>“Let’s leave it running over the weekend,” my coworker said.</p><p>Brilliant plan. Forty-eight hours of uninterrupted GPU mining. We’d come back Monday to a small fortune. Or at least enough to buy lunch.</p><h3>Monday</h3><p>We walked in Monday morning. The workstation was off.</p><p>Not sleeping. Not in standby. Off. Dead. The kind of off where you press the power button and nothing happens, then press it again harder as if force helps with electronics.</p><p>My first thought, and I’m not proud of this, was not about the work we might have lost. It was: “Please don’t let the Tesla card be dead.” That GPU was worth more than my monthly salary.</p><p>We opened the case. Tried different power configurations. Swapped cables. Nothing. Then we put in a spare hard drive, and the machine booted. The old disk had died. Probably already on its way out, and a weekend of continuous GPU mining at full load was the final push.</p><p>The Tesla was fine. The disk was toast. And with it, whatever Bitcoin we’d accumulated over the weekend.</p><h3>The $180 Fix</h3><p>It was lunchtime. We walked to the nearest electronics store and bought a hard drive for about $180. Came back, installed the OS, restored everything, got the workstation back to its original state. Work machine first, mining experiment second.</p><p>Then I remembered: the mining pool. The website should still have our balance. We logged in.</p><p>Seven or eight dollars. That’s what was sitting there.</p><p>I did the math that any reasonable person would do in that moment. We had just spent $180 on a hard drive. We had earned $7. The net result of our Bitcoin mining career was negative $173.</p><p>“This is stupid,” I said. “We just lost money on free money.”</p><p>We closed the browser tab. I never opened that website again. I don’t even remember which mining pool it was.</p><h3>The Math I Wish I Hadn’t Done</h3><p>Bitcoin averaged around $11 in October 2012. Seven or eight dollars in the pool meant we were sitting on roughly 0.7 BTC.</p><p>We closed the tab on 0.7 Bitcoin.</p><p>But that’s not the part that really stings. The part that stings is the $180.</p><p>If instead of buying a hard drive to mine Bitcoin, we had just bought Bitcoin with that $180, we’d have gotten around 16 BTC. Bitcoin has touched $140,000 since then. I’ll let you do that multiplication yourself. I did it once, stared at the ceiling for a while, and decided to never do it again.</p><p>We had $180. We had heard of Bitcoin. We understood it was digital money. And we chose to spend $180 on a spinning metal disk so we could mine $7 worth of it.</p><p>As for that 0.7 BTC still sitting in whatever mining pool we used, I don’t even remember the name. If you ran that pool in 2012 and somehow still have records of an NVIDIA Tesla that mined for four days in October, call me. I’ll buy you a hard drive.</p><h3>The Guy Who Told Me About Bitcoin</h3><p>My coworker who introduced me to Bitcoin? He didn’t buy any either. Neither did anyone else in the office. We were all engineers working with NVIDIA Tesla GPUs, literally the best hardware for mining at the time. We had the tools, the knowledge, and the timing. We had everything except the imagination to take it seriously.</p><p>Because in 2012, Bitcoin wasn’t an investment. It was a curiosity. Something a guy told you about at lunch. You tried it for a weekend, lost a hard drive, and moved on.</p><p>Nobody was wrong for not buying Bitcoin in 2012. Everyone had the same information and almost nobody acted on it. The few who did and held on were either visionary or just forgot their wallet passwords.</p><h3>What I Actually Took Away</h3><p>I don’t tell this story as an investment lesson. “You should have bought Bitcoin” is the most useless advice in history because it only works backwards.</p><p>But I do think about it when I see something new and dismiss it too quickly. We had the right timing. Bitcoin was $11. We were GPU engineers. The setup was perfect. What we got wrong wasn’t the opportunity, it was the approach. We tried to extract value from it in the most literal, mechanical way possible (run program, get money) instead of stepping back and asking a bigger question: what does it mean that strangers on the internet are willing to pay $11 for something that only exists as math?</p><p>If we’d asked that question, maybe we wouldn’t have closed the tab.</p><p>Or maybe we still would have. Eleven dollars for magic internet money sounded ridiculous in 2012. To be fair, it still kind of does. It just sounds ridiculous at a much higher price now.</p><p>The hard drive, by the way, worked great for years.</p><p><em>I’m Burak Hamuryen, a Senior Software Engineer in Berlin with 14+ years of experience building distributed systems, real-time video processing, and cloud-native platforms. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b6163bd521" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Probably Don’t Need Microservices]]></title>
            <link>https://medium.com/@hamuryen/you-probably-dont-need-microservices-1bbc402b1a10?source=rss-5d1e33604f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bbc402b1a10</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[monolith]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Burak Hamuryen]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 06:11:01 GMT</pubDate>
            <atom:updated>2026-10-09T19:31:15.523Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A service boundary should earn its operational cost. Here is how I weigh independent deployment and scaling against the work of running a distributed system.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTzO26u77qvYkluKl75P6Q.png" /><figcaption>One block vs. twenty fragments connected by tangled wires. That’s the trade-off nobody warns you about.</figcaption></figure><p>I watched a 3-person team spend months setting up Kubernetes, Kafka, and a service mesh for an app that could have been a single Spring Boot jar. They were solving infrastructure problems instead of building their product. By the time the architecture was “ready,” they’d burned through half their runway. The product never launched.</p><p>I’ve managed 60 microservices in production for a government platform. Kubernetes, ZeroMQ, Kafka, Docker, the whole stack. It was the right call for that project. But that project had multiple teams, independent deployment requirements, and government-scale traffic. Most projects don’t.</p><p>Microservices can sound like the obvious next step when a system grows. I would want to know which part of the current architecture is actually holding the team back.</p><p>A large company&#39;s architecture is useful evidence about its constraints. It is not a requirement for a smaller team.</p><h3>What Consolidation Cases Actually Show</h3><p>A useful consolidation case explains which costs disappeared and which capabilities the team kept. It does not establish that every distributed system should become a monolith.</p><p><a href="https://www.twilio.com/en-us/blog/developers/best-practices/goodbye-microservices">Segment’s account</a> describes consolidating its destination-delivery workers after separate services and dependency management became expensive to maintain. The lesson is specific: isolation had benefits, but their implementation made routine changes too costly.</p><p>I would use a case like that to investigate a similar bottleneck, not to estimate my own savings. Data movement, orchestration, release coordination, and failure isolation need to be evaluated in the actual workload.</p><p><a href="https://istio.io/latest/blog/2020/istiod/">Istio 1.5 consolidated</a> several control-plane components into istiod. Its maintainers explained that those components were already released and operated together, with limited benefit from separate scaling. This was a packaging decision for the control plane, not a rejection of microservices for the applications using the mesh.</p><h3>What You’re Actually Signing Up For</h3><p>When someone says “let’s use microservices,” here’s what they’re really proposing:</p><p><strong>Network calls instead of function calls. A remote call adds serialization, transport, queueing, and another possible failure boundary. There is no fixed millisecond penalty: measure the deployment and workload. Serial calls can accumulate latency; parallel fan-out makes the slowest required response important. In our auction platform, the path through bidding, user checks, payment validation, and notifications needed careful attention. A faster individual service would not automatically make the whole request faster.</strong></p><p><strong>Distributed debugging. I&#39;ve spent days correlating logs across services to find a serialization mismatch. Shared types can catch some such errors at build time, but neither a monolith nor a successful compile guarantees compatible behavior. Correlation IDs, structured logs, and traces help reconstruct what happened across independently deployed components. That work needs an owner.</strong></p><p><strong>Data integrity crosses a boundary. A relational database still provides transactions and constraints inside each service. The difficulty appears when one business operation needs consistent changes across separately owned databases. A single local transaction can no longer cover the whole operation.</strong></p><p>For example, deleting a user does not automatically decide what should happen to records in another service. Some may need deletion, some anonymization, and some retention. The services need an explicit contract and a way to handle delayed or failed processing. Separate data ownership is useful, but it moves some consistency work into the application.</p><p>Queries spanning services also need a design. API composition and replicated read models are possible approaches; both bring questions about freshness, pagination, and failure handling. This is a different problem from writing a join inside one database.</p><p>Local ACID transactions still exist. For a business operation spanning services, one option is a saga: a sequence of local transactions with explicit recovery or compensating actions. A compensation is not a database rollback, and an external payment is not made atomic merely by moving its caller into a monolith. There is no universal service-count threshold where this becomes unmanageable. The hard part is specifying outcomes when a step, including compensation, fails.</p><p><strong>Operations grow with the number of independently running components. Each needs deployment, monitoring, ownership, and recovery decisions. A platform can share much of that machinery, so multiplying services does not imply a fixed staffing ratio. I would price the work our team still has to do, including maintaining that platform.</strong></p><p><strong>Testing crosses deployment boundaries. Unit tests remain useful, but they do not establish that independently released consumers and producers agree. Contract checks can catch drift before deployment; integration and end-to-end tests cover different risks. Monoliths need interface and integration tests too, particularly when they call external systems. The difference is how many combinations can be running independently.</strong></p><p><strong>Understanding the system takes deliberate work. More components can mean more owners, versions, and failure paths to keep track of. Domain boundaries and documentation help, but a small team still has to operate the result. Service count alone is not a measure of modularity.</strong></p><h3>Questions I Ask Before Adding a Service</h3><p>I want a concrete answer to each of these before accepting another independently deployed component.</p><p><strong>Deployment:</strong></p><blockquote>Which change can this team release independently after the split?</blockquote><p>If every release still needs synchronized changes elsewhere, I would examine the boundary before adding deployment machinery.</p><p><strong>Domain boundaries:</strong></p><blockquote>What have we learned from the working system that makes this a stable boundary?</blockquote><p><strong>Operations:</strong></p><blockquote>Who owns this service when a dependency times out or a deployment fails?</blockquote><blockquote>Which recovery behavior have we actually tested?</blockquote><p><strong>Cost:</strong></p><blockquote>What measured limitation will this split remove?</blockquote><p>These questions are more useful to me than a target service count. The answers can justify a split, or show that a module inside the existing application would do the job.</p><h3>The Distributed Monolith: The Worst of Both Worlds</h3><p>A common failure mode is splitting deployment without reducing coupling. Services may require coordinated releases, rely on one another&#39;s internal tables, or make every feature span several repositories.</p><p>That can leave the team paying for network boundaries while retaining much of the release coordination of a single application.</p><p>Warning signs worth investigating:</p><ul><li>You deploy multiple services together, every time</li><li>A change in one service requires changes in 3 others</li><li>Services read or change one another&#39;s internal database tables</li><li>You can’t test one service without spinning up 5 others</li><li>Your “independent” services call each other synchronously in long chains</li></ul><p>None of these signals alone proves the design is wrong. Look for a repeated inability to change, test, and operate a service within a clear contract.</p><h3>Shopify’s Alternative: The Modular Monolith</h3><p>Shopify&#39;s engineering team described evolving its Rails application into a modular monolith: keeping a shared deployment while establishing clearer component boundaries. It is a useful example of improving modularity without first distributing every module.</p><p>Their Packwerk tooling checks static references against package boundaries. It helps enforce architectural rules, but it does not prove that every runtime interaction is independent.</p><p>The practical appeal of this approach:</p><ol><li>Keep calls within one process where a network boundary offers little benefit</li><li>Improve ownership and dependencies without adding a deployment for every module</li><li>Leave room to extract a service when an actual operational need appears</li></ol><p>A modular monolith needs maintained interfaces and data boundaries. Simply putting everything in one repository does not create those boundaries. Keeping them clear can make a later extraction easier.</p><h3>When Microservices Actually Make Sense</h3><p>I have also worked on projects where separate services were worthwhile. My <a href="https://post.hamuryen.com/e57c161b62b7">C++ video-system migration</a> describes one of those cases. Here are the kinds of needs I would look for:</p><p><strong>Multiple independent teams. We had teams that needed to release on different schedules. Separate services can support that when responsibilities and interfaces are clear; the number of teams alone does not dictate the architecture.</strong></p><p><strong>Genuinely different scaling requirements.</strong> Our auction engine needed to handle thousands of concurrent bids per second. The document management module needed to serve PDFs occasionally. Scaling them together would have been wasteful. This is a real signal.</p><p><strong>Regulatory isolation.</strong> Payment processing under banking regulations needed to be isolated from the rest of the system. Separate service, separate audit trail, separate security boundary.</p><p><strong>Different technology requirements.</strong> If one component genuinely benefits from a different language or runtime. Our real-time bidding engine had different performance characteristics than our reporting module.</p><p><strong>You&#39;ve learned the boundaries. Fowler&#39;s Monolith First argument is useful here: early feedback can reveal where the domain divides before network interfaces make those divisions more expensive to change. That is an argument for learning, not a guarantee that any monolith will be easy to split.</strong></p><h3>The Resume-Driven Development Test</h3><p>I&#39;ve been guilty of picking a technology because I wanted to learn it. Seeing Kafka in job listings is a good reason to study it; it is not sufficient reason to add it to a product. I try to separate the learning project from the architecture decision.</p><p>The honest test: would I still pick this architecture if it didn’t go on my resume? If the answer is “probably not,” that’s worth pausing on.</p><p>Some patterns I’ve seen more than once:</p><ul><li>Breaking an app into 50 services maintained by 2 developers</li><li>Deploying Kubernetes for a project with 500 users</li><li>Adding Kafka when your data flow is request-response</li><li>Implementing a service mesh for 4 services</li></ul><p>None of these are wrong in the right context. But the right context is rarely a startup with 5 engineers and no product-market fit yet.</p><h3>What I’d Actually Recommend</h3><p><strong>Start with a monolith.</strong> Make it modular. Use clear boundaries: separate modules, defined interfaces, no reaching into another module’s database tables. Enforce boundaries with tooling if your language supports it (Packwerk for Ruby, ArchUnit for Java, module boundaries in Go).</p><p><strong>Extract a service when you have a real reason.</strong> Not “we might need to scale this independently someday,” but “this component is currently a bottleneck and we need to scale it now.” Not “this team might want to deploy independently,” but “this team’s deployment schedule is blocked by another team every sprint.”</p><p><strong>For a small team, I would begin by asking whether one deployable application with clear modules meets today&#39;s needs. If it does, independent services need a specific benefit to justify their added work.</strong></p><p><strong>If existing services repeatedly change together and their separation adds little useful isolation or scaling flexibility, consolidation is worth testing. Measure delivery time, incidents, resource use, and recovery before and after the change.</strong></p><p>Choose boundaries that make the system easier to change and operate. Keep the ones that earn their cost, and revisit the ones that don’t. <em>Updated October 9, 2026: removed an unverified survey statistic and unsupported numerical rules, and clarified the case studies and transaction discussion.</em></p><h3>Further Reading</h3><p><strong>Case Studies:</strong></p><ul><li><a href="https://istio.io/latest/blog/2020/istiod/">Istio: consolidating the control plane into istiod</a></li><li><a href="https://www.infoq.com/news/2018/07/segment-microservices/">Segment: Goodbye Microservices</a></li><li><a href="https://shopify.engineering/deconstructing-monolith-designing-software-maximizes-developer-productivity">Shopify: Deconstructing the Monolith</a></li><li><a href="https://www.uber.com/us/en/blog/microservice-architecture/">Uber: Domain-Oriented Microservice Architecture</a></li></ul><p><strong>Perspectives:</strong></p><ul><li><a href="https://martinfowler.com/bliki/MonolithFirst.html">Martin Fowler: MonolithFirst</a></li><li><a href="https://world.hey.com/dhh/how-to-recover-from-microservices-ce3803cc">DHH: How to Recover from Microservices</a></li><li><a href="https://changelog.com/posts/monoliths-are-the-future">Kelsey Hightower: Monoliths Are the Future</a></li><li><a href="https://samnewman.io/books/monolith-to-microservices/">Sam Newman: Monolith to Microservices</a></li></ul><p><strong>Technical references:</strong></p><ul><li><a href="https://microservices.io/patterns/data/saga.html">Chris Richardson: the Saga pattern</a></li><li><a href="https://research.google/pubs/the-tail-at-scale/">The Tail at Scale (Jeff Dean, Google)</a></li><li><a href="https://shopify.engineering/enforcing-modularity-rails-apps-packwerk">Shopify: enforcing modularity with Packwerk</a></li></ul><p><em>I’m Burak Hamuryen, a Senior Software Engineer in Berlin with 14+ years of experience building distributed systems, real-time video processing, and cloud-native platforms. More at </em><a href="https://hamuryen.com/"><em>hamuryen.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bbc402b1a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>