<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Eduardo Teixeira</title>
    <description>The latest articles on DEV Community by Eduardo Teixeira (@dunirvana).</description>
    <link>https://dev.to/dunirvana</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F241501%2Ff66f6684-1499-4b98-9828-bdbfba7238e8.jpeg</url>
      <title>DEV Community: Eduardo Teixeira</title>
      <link>https://dev.to/dunirvana</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dunirvana"/>
    <language>en</language>
    <item>
      <title>Concurrent calls with asyncio: timeouts and graceful degradation</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Thu, 26 Nov 2026 14:42:39 +0000</pubDate>
      <link>https://dev.to/dunirvana/concurrent-calls-with-asyncio-timeouts-and-graceful-degradation-5bjj</link>
      <guid>https://dev.to/dunirvana/concurrent-calls-with-asyncio-timeouts-and-graceful-degradation-5bjj</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/concurrent-calls-asyncio-taskgroup.html" rel="noopener noreferrer"&gt;Chamadas concorrentes com asyncio, timeout e degradação graciosa&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You know that screen that needs data from three different services? Customer profile, recent orders, recommendations. The most common way to write it is to call one after the other with &lt;code&gt;await&lt;/code&gt;, and the result is that the screen takes the sum of all the calls. Worse: when the recommendations service chokes, the whole screen chokes with it, even though nobody cares that much about recommendations.&lt;/p&gt;

&lt;p&gt;In this post I show a small aggregator that solves both problems: it calls everything at the same time with &lt;code&gt;asyncio.TaskGroup&lt;/code&gt;, puts a timeout on each call, and decides what is required and what can be left out.&lt;/p&gt;

&lt;h2&gt;
  
  
  The core idea
&lt;/h2&gt;

&lt;p&gt;The business rule is simple. The customer profile is required: without it there's no dashboard. Orders and recommendations are optional: if they take too long or return an error, the dashboard goes out without them, and the response says which sections were left out, in the &lt;code&gt;degraded&lt;/code&gt; field. The front end decides what to show instead.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;TaskGroup&lt;/code&gt; fits this well because of its default behavior: if one task raises an exception, its siblings are cancelled. For the required call that's exactly what I want. For the optional ones it's the opposite, so they catch their own error and return a result instead of raising.&lt;/p&gt;

&lt;h2&gt;
  
  
  Firing the three calls
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;build&lt;/code&gt; method creates the three tasks inside the group. When the &lt;code&gt;async with&lt;/code&gt; block ends, they have all finished, and then it's just a matter of calling &lt;code&gt;result()&lt;/code&gt;. If something escapes the group, it arrives as an &lt;code&gt;ExceptionGroup&lt;/code&gt;, and I translate it into the two domain exceptions, &lt;code&gt;CustomerNotFound&lt;/code&gt; and &lt;code&gt;ProfileUnavailable&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Dashboard&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;TaskGroup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;group&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;profile&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;group&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_task&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_fetch_profile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;group&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_task&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_fetch_optional&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"/customers/{customer_id}/orders"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;recommendations&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;group&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_task&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                    &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_fetch_optional&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"/customers/{customer_id}/recommendations"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;ExceptionGroup&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;errors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;errors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subgroup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CustomerNotFound&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;CustomerNotFound&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;ProfileUnavailable&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;errors&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I used a regular &lt;code&gt;except ExceptionGroup&lt;/code&gt; with &lt;code&gt;subgroup&lt;/code&gt; because I need to look at what came inside the group before deciding which domain exception to raise: if there's a &lt;code&gt;CustomerNotFound&lt;/code&gt; in there, the response is a 404, and anything else becomes a 502. The &lt;code&gt;from None&lt;/code&gt; in the first case avoids dragging the whole group into the traceback of an error that is expected.&lt;/p&gt;

&lt;h2&gt;
  
  
  Timeout and concurrency limit
&lt;/h2&gt;

&lt;p&gt;Every call goes through &lt;code&gt;_fetch&lt;/code&gt;. The &lt;code&gt;asyncio.Semaphore&lt;/code&gt; limits how many requests are in flight at the same time (useful when the same aggregator serves a lot of people and you don't want to drown the service behind it), and &lt;code&gt;asyncio.timeout&lt;/code&gt; cuts the wait. Note that the timeout sits inside the semaphore: time spent waiting in the queue doesn't count against the call.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Any&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_timeout&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{self._base_url}{path}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;raise_for_status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When &lt;code&gt;asyncio.timeout&lt;/code&gt; expires it raises &lt;code&gt;TimeoutError&lt;/code&gt;, the same built-in Python type, so there's no special exception to import.&lt;/p&gt;

&lt;h2&gt;
  
  
  Degrading instead of failing
&lt;/h2&gt;

&lt;p&gt;The optional call swallows the expected errors, a timeout or any &lt;code&gt;httpx.HTTPError&lt;/code&gt;, and returns a &lt;code&gt;Section&lt;/code&gt; with &lt;code&gt;error="unavailable"&lt;/code&gt;. Since it never raises, the &lt;code&gt;TaskGroup&lt;/code&gt; doesn't cancel anyone because of it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_fetch_optional&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Section&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Section&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TimeoutError&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;HTTPError&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Section&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"unavailable"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Testing without a network
&lt;/h2&gt;

&lt;p&gt;In the tests I swap the upstream for an &lt;code&gt;httpx.MockTransport&lt;/code&gt; with an async handler, so I can simulate slowness with &lt;code&gt;asyncio.sleep&lt;/code&gt; without starting anything. The test below makes recommendations slow, with a 0.1 second timeout, and checks that the dashboard comes out without them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;test_slow_optional_call_degrades_instead_of_failing&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;upstream&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FakeUpstream&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;delays&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"recommendations"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;aggregator&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;make_aggregator&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;upstream&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;dashboard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;aggregator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;dashboard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recommendations&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"unavailable"&lt;/span&gt;
    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;dashboard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recommendations&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;dashboard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;dashboard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;degraded&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"recommendations"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There's also a test that measures the maximum number of simultaneous calls in the handler: with three calls released the peak is 3, and with &lt;code&gt;max_concurrency=1&lt;/code&gt; the peak is 1. Stopwatch-based concurrency tests are fragile, so this counter is more reliable than comparing times (the timing test exists, but with a generous margin). Each test creates its own aggregator, so there's no shared state between them.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to run it with Docker
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;docker-compose.yml&lt;/code&gt; starts two services: &lt;code&gt;upstream&lt;/code&gt;, which simulates the dependencies with configurable delays, and &lt;code&gt;app&lt;/code&gt;, which is the aggregator. Recommendations take 2 seconds on purpose, longer than the 0.5 second timeout, so the very first call already shows the degradation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose up --build

curl localhost:8000/customers/1/dashboard
curl localhost:8000/customers/99/dashboard

docker compose run --rm tests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first response comes back with &lt;code&gt;"degraded": ["recommendations"]&lt;/code&gt; in about half a second, instead of the 2 seconds the slow call would take. The second returns a 404. Play with &lt;code&gt;RECOMMENDATIONS_DELAY&lt;/code&gt; and &lt;code&gt;UPSTREAM_TIMEOUT&lt;/code&gt; in the compose file and watch the result change.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;The pattern is small, but it solves a problem that shows up in almost every API that aggregates data: separating what is essential from what is decoration, and not letting the decoration take down the response. The full code, with tests, Dockerfile and compose, is at &lt;a href="https://github.com/dunirvana/programero-python/tree/main/2026-11-concurrent-calls-asyncio-taskgroup" rel="noopener noreferrer"&gt;programero-python/2026-11-concurrent-calls-asyncio-taskgroup&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>asyncio</category>
      <category>fastapi</category>
      <category>docker</category>
    </item>
    <item>
      <title>Nvidia without Jensen Huang: the resignation, the earnings and the GPU/CUDA concentration risk</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Sat, 21 Nov 2026 22:47:16 +0000</pubDate>
      <link>https://dev.to/dunirvana/nvidia-without-jensen-huang-the-resignation-the-earnings-and-the-gpucuda-concentration-risk-1o8f</link>
      <guid>https://dev.to/dunirvana/nvidia-without-jensen-huang-the-resignation-the-earnings-and-the-gpucuda-concentration-risk-1o8f</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/nvidia-sem-jensen-huang-risco-de-concentracao.html" rel="noopener noreferrer"&gt;Nvidia sem Jensen Huang: renúncia, balanço e risco de concentração em GPU/CUDA&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In 33 years of history, Nvidia has had only one CEO. Last Thursday, November 12, that ended: Jensen Huang resigned as chairman, CEO and board member, effective immediately. The CFO, Colette Kress, took over as interim CEO while the board searches for a successor. Harvey Jones, on the board since 1993, became the first chair of the board in the company's history.&lt;/p&gt;

&lt;h2&gt;
  
  
  What happened
&lt;/h2&gt;

&lt;p&gt;The official announcement gives no reason. What is known comes from the press. The New York Times and the Financial Times reported in the previous weeks that Huang had a relationship with an executive who, according to the reports, was the target of a Chinese intelligence operation, and the board hired an independent investigation. The day before the resignation, the New York Times added that there was a second relationship, with a vice president who reported directly to him, and the Wall Street Journal said the board was preparing to remove him. Nvidia didn't confirm these reports, so it's worth treating them as reporting, not settled fact.&lt;/p&gt;

&lt;p&gt;The stock fell more than 10% at the open that day. Five days later, Nvidia released results for the quarter ended in October, the first without Huang: revenue of US$ 115.8 billion, up 103% year over year, with US$ 107.6 billion coming from data center. Guidance for the next quarter is US$ 130 billion, without counting any data center compute sales to China. In other words, the machine keeps running.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why this matters if you work in tech
&lt;/h2&gt;

&lt;p&gt;First, the obvious: nothing breaks today. CUDA still compiles, the published product roadmap still stands, and the Rubin platform is already shipping. Analysts quoted in the press say much of the next two years is already contracted and designed. If your training and inference pipeline is stable, the CEO's resignation is no reason to touch it.&lt;/p&gt;

&lt;p&gt;The more interesting point is a different one. Analysts described Nvidia as a company built around one person, with no named successor, where many decisions about pace and priorities went through him. That matters because almost everyone building AI today depends on this company: clouds, startups, in-house data teams. A consultancy cited by CIO recommended exactly this to technology leaders: don't overreact, but use the moment to review concentration risk in AI infrastructure suppliers.&lt;/p&gt;

&lt;p&gt;For developers, the message is more concrete. According to Nvidia's own annual report, more than 7.5 million developers use CUDA and its tools. It's a huge ecosystem, and that coupling is exactly what makes switching vendors expensive. I see no reason to migrate anything because of a governance crisis. But I do see a reason to ask a question almost nobody asks until they have to: if tomorrow I had to run this on other hardware, how much of my code is glued to a specific API and how much sits behind a layer I control? Finding out the answer costs an afternoon. Finding out at the wrong time costs a quarter.&lt;/p&gt;

&lt;h2&gt;
  
  
  My take
&lt;/h2&gt;

&lt;p&gt;There's a parallel with our day-to-day that seems more useful to me than the gossip. Every team knows the bus factor, that person who, if they leave, takes with them the knowledge nobody documented. Nvidia is worth trillions and had the same problem, just at industry scale. The successor most cited by analysts is Ian Buck, the engineer who helped create CUDA and now runs the data center business, and other outside names, like Arm's CEO, show up on the lists. If the pick is a technical profile from inside, the roadmap should stay as it is. If someone comes from outside, the conversation changes.&lt;/p&gt;

&lt;p&gt;I also think the story has an uncomfortable side for the whole industry: an executive's personal life became a national security issue and an AI supply chain issue at the same time. When a technology's infrastructure depends this much on one company, any fragility of theirs becomes everyone's fragility. It's worth watching the succession process over the next few weeks, because it will say more about the platform's future than any headline about the resignation.&lt;/p&gt;

&lt;p&gt;Sources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://nvidianews.nvidia.com/news/nvidia-announces-ceo-transition" rel="noopener noreferrer"&gt;NVIDIA Announces CEO Transition (Nvidia)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://investor.nvidia.com/news/press-release-details/2026/NVIDIA-Announces-Financial-Results-for-Third-Quarter-Fiscal-2027/default.aspx" rel="noopener noreferrer"&gt;NVIDIA Announces Financial Results for Third Quarter Fiscal 2027 (Nvidia)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://techcrunch.com/?p=3187751" rel="noopener noreferrer"&gt;Nvidia's Jensen Huang resigns, chipmaker names CFO Colette Kress as interim CEO (TechCrunch)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.techtarget.com/news/nvidia-ceos-departure-could-pose-risk-over-time-for-it-buyers/874468/" rel="noopener noreferrer"&gt;Nvidia CEO's departure could pose risk over time for IT buyers (TechTarget)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.cio.com/article/4248546/nvidias-leadership-crisis-puts-enterprise-ais-dependence-on-one-company-under-scrutiny-2.html" rel="noopener noreferrer"&gt;Nvidia's leadership crisis puts enterprise AI's dependence on one company under scrutiny (CIO)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.axios.com/2026/11/12/nvidia-next-ceo-jensen-huang-predictions" rel="noopener noreferrer"&gt;11 names to watch in the Jensen Huang succession search (Axios)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.theneuron.ai/news/jensen-huang-resigns-nvidia-future/" rel="noopener noreferrer"&gt;Jensen Huang resigns: Nvidia's future (The Neuron)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>nvidia</category>
      <category>ai</category>
      <category>cuda</category>
      <category>news</category>
    </item>
    <item>
      <title>Duplicate refunds from scattered status checks: fixing it with the State pattern in C#</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Sat, 21 Nov 2026 22:46:48 +0000</pubDate>
      <link>https://dev.to/dunirvana/duplicate-refunds-from-scattered-status-checks-fixing-it-with-the-state-pattern-in-c-382m</link>
      <guid>https://dev.to/dunirvana/duplicate-refunds-from-scattered-status-checks-fixing-it-with-the-state-pattern-in-c-382m</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/order-status-state-pattern.html" rel="noopener noreferrer"&gt;Status de pedido com if espalhado gera estorno duplo -&amp;gt; State&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Every order system has an &lt;code&gt;Order&lt;/code&gt; class with a &lt;code&gt;Status&lt;/code&gt; property. At first there are three or four statuses, each action checks the current status with an &lt;code&gt;if&lt;/code&gt;, and everything is fine. The trouble shows up months later, when a new status arrives and nobody remembers all the places that needed to know about it. In this post I'll show a very concrete case of that, a refund paid twice, and how the State pattern solves it without ceremony.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem
&lt;/h2&gt;

&lt;p&gt;The order goes through &lt;code&gt;Pending&lt;/code&gt;, &lt;code&gt;Paid&lt;/code&gt;, &lt;code&gt;Shipped&lt;/code&gt; and &lt;code&gt;Delivered&lt;/code&gt;, and it can be cancelled before shipping. If it was already paid, cancelling issues a refund. The &lt;code&gt;Cancel()&lt;/code&gt; method in the "before" version is the kind of code everyone has written:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt; &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;Cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Status&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Shipped&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Delivered&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Cancelled&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;InvalidOperationException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;$&lt;span class="s2"&gt;"Cannot cancel an order that is {Status}."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Status&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Pending&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="nc"&gt;RefundCount&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="nc"&gt;Status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Cancelled&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Look at the first condition: it's a list of what is &lt;em&gt;not&lt;/em&gt; allowed. And the second one assumes that anything that isn't &lt;code&gt;Pending&lt;/code&gt; has been paid. As long as the enum had only those statuses, both assumptions were true.&lt;/p&gt;

&lt;p&gt;Then the business asked for returns. Someone created the &lt;code&gt;Returned&lt;/code&gt; status and the new method, with a refund:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt; &lt;span class="c1"&gt;// Added later, when returns became a requirement.&lt;/span&gt;
 &lt;span class="c1"&gt;// Nobody remembered to update Cancel().&lt;/span&gt;
 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nc"&gt;Return&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Status&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Delivered&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;InvalidOperationException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;$&lt;span class="s2"&gt;"Cannot return an order that is {Status}."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="nc"&gt;RefundCount&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="nc"&gt;Status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Returned&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Return()&lt;/code&gt; is correct. The bug is in &lt;code&gt;Cancel()&lt;/code&gt;, which nobody opened: &lt;code&gt;Returned&lt;/code&gt; isn't in the forbidden list and isn't &lt;code&gt;Pending&lt;/code&gt;, so a returned order can be cancelled and the customer gets refunded a second time. No test broke, because the existing tests didn't know &lt;code&gt;Returned&lt;/code&gt; existed. In the project I left a test, &lt;code&gt;Cancelling_a_returned_order_refunds_twice&lt;/code&gt;, that documents exactly this behavior in the old version.&lt;/p&gt;

&lt;p&gt;That's the real pain of the status-based &lt;code&gt;if&lt;/code&gt;: each status's rules end up scattered across every method. To add a status you have to review every action, and the compiler doesn't warn you about any of them.&lt;/p&gt;

&lt;h2&gt;
  
  
  The solution: the State pattern
&lt;/h2&gt;

&lt;p&gt;The idea is to flip the question. Instead of every action asking "what status am I in?", each status becomes a class that knows which actions it accepts. The order only holds the current state and delegates to it. The base class forbids everything by default:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Base state: every action is forbidden unless a state allows it.&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;abstract&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;abstract&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt; &lt;span class="nc"&gt;Status&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;virtual&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt; &lt;span class="nc"&gt;Pay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;NotAllowed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"pay"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;virtual&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt; &lt;span class="nc"&gt;Ship&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;NotAllowed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"ship"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;virtual&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt; &lt;span class="nc"&gt;Deliver&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;NotAllowed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"deliver"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;virtual&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt; &lt;span class="nc"&gt;Cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;NotAllowed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"cancel"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;virtual&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt; &lt;span class="nc"&gt;Return&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;NotAllowed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"return"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;InvalidOperationException&lt;/span&gt; &lt;span class="nc"&gt;NotAllowed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
 &lt;span class="k"&gt;new&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;$&lt;span class="s2"&gt;"Cannot {action} an order that is {Status}."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This "forbidden by default" is the most important point of the design. A new state is born with no permissions at all, and you explicitly allow what makes sense. It's the opposite of the old &lt;code&gt;Cancel()&lt;/code&gt;'s forbidden list.&lt;/p&gt;

&lt;p&gt;Each state overrides only what it allows and returns the next state. The refund for a cancellation lives where it makes sense, in &lt;code&gt;PaidState&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;sealed&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaidState&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt; &lt;span class="nc"&gt;Status&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Paid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt; &lt;span class="nc"&gt;Ship&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ShippedState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

 &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="nc"&gt;OrderState&lt;/span&gt; &lt;span class="nc"&gt;Cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
 &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;IssueRefund&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;CancelledState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Order&lt;/code&gt; class in the "after" version became trivial: a &lt;code&gt;_state&lt;/code&gt; field that starts as &lt;code&gt;PendingState&lt;/code&gt;, and each action is a one-liner like &lt;code&gt;public void Cancel() =&amp;gt; _state = _state.Cancel(this);&lt;/code&gt;. The refund is done by &lt;code&gt;IssueRefund()&lt;/code&gt;, marked &lt;code&gt;internal&lt;/code&gt; so that only the states, in the same assembly, can call it.&lt;/p&gt;

&lt;p&gt;And &lt;code&gt;ReturnedState&lt;/code&gt;? It only declares its own &lt;code&gt;Status&lt;/code&gt;. It doesn't override &lt;code&gt;Cancel&lt;/code&gt;, so cancelling a returned order throws &lt;code&gt;InvalidOperationException&lt;/code&gt; with "Cannot cancel an order that is Returned." without anyone having to remember it.&lt;/p&gt;

&lt;h2&gt;
  
  
  What changed in practice
&lt;/h2&gt;

&lt;p&gt;First, the bug goes away by construction, not by discipline. The &lt;code&gt;Cancelling_a_returned_order_is_rejected&lt;/code&gt; test checks that the cancellation is refused, that the status stays &lt;code&gt;Returned&lt;/code&gt; and that &lt;code&gt;RefundCount&lt;/code&gt; stays at 1.&lt;/p&gt;

&lt;p&gt;Second, reading the code changes. To know what a paid order can do, you open &lt;code&gt;PaidState&lt;/code&gt; and everything is there, in a few lines. In the old version you had to read the five methods of &lt;code&gt;Order&lt;/code&gt; and assemble the state machine in your head.&lt;/p&gt;

&lt;p&gt;Third, extension becomes local. A new status, like "being picked" or "awaiting pickup", is a new class plus a tweak to the state that leads to it. The other states aren't touched. Tests also get more direct: each transition has a short test, and refusals are tested by the exception message.&lt;/p&gt;

&lt;h2&gt;
  
  
  When NOT to use it
&lt;/h2&gt;

&lt;p&gt;State has a cost, and it's not a small one. You trade one file for several, and whoever arrives at the code has to understand the pattern before finding where each rule lives. For a three-status flow that never changes, a well-written &lt;code&gt;switch&lt;/code&gt; is more honest and easier to read.&lt;/p&gt;

&lt;p&gt;It also isn't worth it when the transitions are basically data, with no behavior: if all you need is "from A you can go to B or C", a transition table (a dictionary, or even a database table) solves it with less code and lets you change it without a deploy. State shines when each transition carries its own behavior, like the refund here, sending an email or reserving stock.&lt;/p&gt;

&lt;p&gt;Another thing to watch is persistence. In the database you keep storing the &lt;code&gt;Status&lt;/code&gt; enum, and when loading the order you need to rebuild the state object from it. It's a simple mapping, but it's one more piece to maintain. And if the states start accumulating dependencies (repositories, payment gateways), stop and think: maybe the rule belongs in an application service, and the state should only say whether the transition is allowed.&lt;/p&gt;

&lt;p&gt;My rule of thumb: if you've already fixed a bug because of a status forgotten in some &lt;code&gt;if&lt;/code&gt;, or if the status enum got its fifth value, State is worth considering.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to run it
&lt;/h2&gt;

&lt;p&gt;The project has both versions side by side, in the &lt;code&gt;Before&lt;/code&gt; and &lt;code&gt;After&lt;/code&gt; folders, with tests for each. All you need is Docker installed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd&lt;/span&gt; 2026-11-order-status-state-pattern
docker compose run --rm tests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The full code is on GitHub: &lt;a href="https://github.com/dunirvana/programero-csharp/tree/main/2026-11-order-status-state-pattern" rel="noopener noreferrer"&gt;programero-csharp/2026-11-order-status-state-pattern&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>designpatterns</category>
      <category>cleancode</category>
    </item>
    <item>
      <title>Background processing in .NET 8 with BackgroundService and Channel</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Thu, 19 Nov 2026 13:16:53 +0000</pubDate>
      <link>https://dev.to/dunirvana/background-processing-in-net-8-with-backgroundservice-and-channel-3ff2</link>
      <guid>https://dev.to/dunirvana/background-processing-in-net-8-with-backgroundservice-and-channel-3ff2</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/background-service-channel.html" rel="noopener noreferrer"&gt;Processando em segundo plano no .NET 8 com BackgroundService e Channel&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;We've all been there: the endpoint receives a request, does something slow (generates a report, sends an email, calls a slow service) and the client sits waiting until it times out. The classic way out is to respond right away and do the work in the background. You can jump straight to a broker like RabbitMQ, but that's often overkill. In .NET 8 you already have what you need at home: &lt;code&gt;BackgroundService&lt;/code&gt; and &lt;code&gt;Channel&amp;lt;T&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The idea
&lt;/h2&gt;

&lt;p&gt;The API doesn't process anything. It registers the job, puts it in a queue and returns &lt;code&gt;202 Accepted&lt;/code&gt; with a &lt;code&gt;Location&lt;/code&gt; header. On the other side, a &lt;code&gt;BackgroundService&lt;/code&gt; loops reading from the queue and processing one job at a time. The client polls &lt;code&gt;GET /jobs/{id}&lt;/code&gt; to get the status: &lt;code&gt;Queued&lt;/code&gt;, &lt;code&gt;Processing&lt;/code&gt;, &lt;code&gt;Completed&lt;/code&gt; or &lt;code&gt;Failed&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The project has three pieces: &lt;code&gt;ChannelJobQueue&lt;/code&gt; (the queue), &lt;code&gt;JobStore&lt;/code&gt; (a concurrent dictionary with the state of each job) and &lt;code&gt;JobWorker&lt;/code&gt; (the consumer). Everything is in memory, on purpose, to keep the mechanism visible.&lt;/p&gt;

&lt;h2&gt;
  
  
  The queue
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Channel.CreateBounded&lt;/code&gt; creates a channel with a fixed capacity, and that choice matters: without a limit, a burst of requests turns into uncontrolled memory growth. With a limit, you decide what happens when it fills up. In &lt;code&gt;ChannelJobQueue&lt;/code&gt;, the &lt;code&gt;TryEnqueue&lt;/code&gt; method uses &lt;code&gt;TryWrite&lt;/code&gt;, which returns &lt;code&gt;false&lt;/code&gt; immediately if there is no room, instead of holding the request waiting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;sealed&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ChannelJobQueue&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;IJobQueue&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="nc"&gt;Channel&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Job&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;_channel&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ChannelJobQueue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;_channel&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Channel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CreateBounded&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Job&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;BoundedChannelOptions&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;FullMode&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;BoundedChannelFullMode&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Wait&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="nc"&gt;SingleReader&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;// Returns false immediately when the queue is full, instead of waiting.&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nc"&gt;TryEnqueue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Job&lt;/span&gt; &lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;_channel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Writer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;TryWrite&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The endpoint
&lt;/h2&gt;

&lt;p&gt;In &lt;code&gt;POST /jobs&lt;/code&gt; the order matters: first &lt;code&gt;store.Add&lt;/code&gt;, then &lt;code&gt;TryEnqueue&lt;/code&gt;. If it were the other way around, the worker could pick up the job before it exists in the &lt;code&gt;JobStore&lt;/code&gt; and try to update an unknown id. If the queue is full, I remove the job from the store and respond with 503 using &lt;code&gt;Results.Problem&lt;/code&gt;. That's backpressure reaching the client: better to say "try again in a bit" than to accept what you can't handle.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;job&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Job&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Guid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;NewGuid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Register the job before enqueueing, so the worker never sees an unknown id.&lt;/span&gt;
&lt;span class="n"&gt;store&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;TryEnqueue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;store&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Results&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Problem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;statusCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;StatusCodes&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Status503ServiceUnavailable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Queue is full."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Results&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Accepted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;$&lt;span class="s2"&gt;"/jobs/{job.Id}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Id&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The worker
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;JobWorker&lt;/code&gt; inherits from &lt;code&gt;BackgroundService&lt;/code&gt; and implements &lt;code&gt;ExecuteAsync&lt;/code&gt;. The &lt;code&gt;await foreach&lt;/code&gt; over &lt;code&gt;DequeueAllAsync&lt;/code&gt; (which is &lt;code&gt;ReadAllAsync&lt;/code&gt; on the channel underneath) sleeps when the queue is empty and wakes up when an item arrives, with no polling and no &lt;code&gt;Task.Delay&lt;/code&gt; in a loop. When the host receives the stop signal, &lt;code&gt;stoppingToken&lt;/code&gt; is cancelled, the enumerator throws &lt;code&gt;OperationCanceledException&lt;/code&gt; and I just log the shutdown.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nc"&gt;Task&lt;/span&gt; &lt;span class="nc"&gt;ExecuteAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CancellationToken&lt;/span&gt; &lt;span class="n"&gt;stoppingToken&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;job&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DequeueAllAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;stoppingToken&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;ProcessAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stoppingToken&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;OperationCanceledException&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;when&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;stoppingToken&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;IsCancellationRequested&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;LogInformation&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Worker is shutting down."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The other thing to watch is failure. If an exception escapes the loop, &lt;code&gt;ExecuteAsync&lt;/code&gt; ends and the worker dies silently: the API keeps accepting jobs that nobody processes anymore. That's why &lt;code&gt;ProcessAsync&lt;/code&gt; catches the exception for each job, marks it as &lt;code&gt;Failed&lt;/code&gt; and moves on to the next one. The &lt;code&gt;when (ex is not OperationCanceledException)&lt;/code&gt; filter lets the shutdown cancellation through.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;when&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ex&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="nc"&gt;OperationCanceledException&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// One bad job must not kill the worker loop.&lt;/span&gt;
    &lt;span class="n"&gt;store&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SetStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;JobStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Failed&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;logger&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;LogError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Job {JobId} failed."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;p&gt;The tests use &lt;code&gt;WebApplicationFactory&lt;/code&gt;, one instance per test, since the queue and the store are in-memory singletons. &lt;code&gt;Worker:DelayMs&lt;/code&gt; and &lt;code&gt;Queue:Capacity&lt;/code&gt; are set through &lt;code&gt;AddInMemoryCollection&lt;/code&gt;. The most interesting test is the full-queue one: with capacity 1 and the worker busy for 3 seconds, the first job becomes &lt;code&gt;Processing&lt;/code&gt;, the second takes the queue slot and the third gets a 503. Waiting for the &lt;code&gt;Processing&lt;/code&gt; status before sending the second one avoids a race between the test and the worker.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;factory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CreateFactory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;delayMs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CreateClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// The worker takes the first job and stays busy with it.&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;firstId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;CreateJobAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"first"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;WaitForStatusAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;firstId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Processing"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// The second job fills the queue (capacity 1).&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;CreateJobAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"second"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// The third one has no room left.&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;PostAsJsonAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/jobs"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"third"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;Assert&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;HttpStatusCode&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ServiceUnavailable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;StatusCode&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are also tests for the 202, the 400, the 404, a job that completes, and a worker that survives a failing job (the name &lt;code&gt;fail&lt;/code&gt; simulates the error).&lt;/p&gt;

&lt;h2&gt;
  
  
  Running with Docker
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;docker-compose.yml&lt;/code&gt; has the &lt;code&gt;app&lt;/code&gt; service, which brings up the API on port 8080, and the &lt;code&gt;tests&lt;/code&gt; service, which runs xUnit. With the API up, just create a job and check its status:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose up --build
curl -X POST http://localhost:8080/jobs -H &lt;span class="s2"&gt;"Content-Type: application/json"&lt;/span&gt; -d &lt;span class="s1"&gt;'{"name":"report"}'&lt;/span&gt;
curl http://localhost:8080/jobs/&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;id&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
docker compose run --rm tests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  When this isn't enough
&lt;/h2&gt;

&lt;p&gt;An in-memory queue doesn't survive a restart and doesn't share work across multiple instances. If the job can't be lost, or if you have more than one replica, the way to go is a broker (RabbitMQ, Azure Service Bus) or an outbox table. For short, loss-tolerant tasks, like notifications or cache warming, &lt;code&gt;Channel&lt;/code&gt; does the job with very little code.&lt;/p&gt;

&lt;p&gt;The full code is here: &lt;a href="https://github.com/dunirvana/programero-csharp/tree/main/2026-11-background-service-channel" rel="noopener noreferrer"&gt;programero-csharp/2026-11-background-service-channel&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>docker</category>
      <category>backend</category>
    </item>
    <item>
      <title>.NET 8 and .NET 9 lost support on the day of the biggest Patch Tuesday ever</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Sun, 15 Nov 2026 12:58:05 +0000</pubDate>
      <link>https://dev.to/dunirvana/net-8-and-net-9-lost-support-on-the-day-of-the-biggest-patch-tuesday-ever-1ehg</link>
      <guid>https://dev.to/dunirvana/net-8-and-net-9-lost-support-on-the-day-of-the-biggest-patch-tuesday-ever-1ehg</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/dotnet-8-e-9-sem-suporte.html" rel="noopener noreferrer"&gt;.NET 8 e .NET 9 saíram de suporte no dia do maior Patch Tuesday da história&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;On Tuesday, November 10, two things happened that look like separate news items and that, in my opinion, are the same story. .NET 8 and .NET 9 went out of support. And on the same day Microsoft shipped the largest Patch Tuesday I've ever seen: close to 1,100 security fixes, depending on who is counting.&lt;/p&gt;

&lt;h2&gt;
  
  
  What happened
&lt;/h2&gt;

&lt;p&gt;The schedule had been announced since June. On November 10, 2026, .NET 8 (LTS) and .NET 9 (STS) stopped receiving security fixes and technical support. .NET 9 ended together with 8 because the support window for STS releases was stretched from 18 to 24 months, and the math landed on the same date. The official recommendation is to move to .NET 10, which is LTS and supported until November 2028. Your application keeps running, nobody is going to switch anything off, but whatever gets discovered from now on won't be fixed for those versions.&lt;/p&gt;

&lt;p&gt;As for Patch Tuesday, according to Krebs on Security it fixed 1,093 vulnerabilities, 63 of them critical and one actively exploited: a spoofing flaw in Outlook (CVE-2026-124194). Other outlets counted 1,094, 1,095 or even 1,235, because each one decides differently what goes into the tally (first-party products, third-party components, cloud service flaws). What matters is the order of magnitude. A year ago the monthly average was around 100 fixes. October had more than 1,400, and the 2026 total is already past 5,100. Microsoft itself attributes the jump to the evolution of artificial intelligence in the search for flaws.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why this matters if you work in tech
&lt;/h2&gt;

&lt;p&gt;For years, "upgrade the framework version" sat in the backlog with a tech-debt label and low priority. The argument was reasonable: if it works, don't touch it. But that argument assumes the pace of flaw discovery is slow and predictable. When the volume of published vulnerabilities grows tenfold in a year, running an unsupported version stops being an abstract risk and becomes a window that stays open and visible to anyone who reads the bulletins.&lt;/p&gt;

&lt;p&gt;There's also the less glamorous side: many people don't get to choose the version. Anyone who works with enterprise systems knows that one .NET 8 application running on a server managed by another team, under a contract with a vendor who "will still evaluate the migration". For that scenario, Microsoft's guidance is direct: ask the vendor for an updated version. And if you use Visual Studio 2022, an upcoming update will flag the .NET 8 and 9 components as out of support, so it's worth checking your installer settings before being surprised.&lt;/p&gt;

&lt;p&gt;A number from Chris Goettl, at Ivanti, helps put it in perspective: of roughly 95,000 CVEs assigned in 2026, only 217 made it onto CISA's list of known exploited vulnerabilities. In other words, the vast majority of flaws never turn into attacks. But nobody knows in advance which one will be the next of those 217, and that's where a framework without fixes weighs more than an up-to-date operating system.&lt;/p&gt;

&lt;h2&gt;
  
  
  My take
&lt;/h2&gt;

&lt;p&gt;I think we're entering a phase where the software lifecycle becomes an architecture decision, not a footnote. When flaws were discovered slowly, you could live one version behind without much anxiety. With accelerated discovery, the time between "known flaw" and "exploited flaw" shrinks, and the advantage of being on a maintained version grows in the same proportion.&lt;/p&gt;

&lt;p&gt;No need to panic either. Moving from .NET 8 to 10 is usually, in most projects, a change of the &lt;em&gt;TargetFramework&lt;/em&gt;, a round of tests and a careful read of the breaking changes. What really takes work are the old dependencies, the pipelines pinned to specific container images and the hosting environments nobody has updated in two years. If you haven't yet inventoried which services run on which version, this week is a good time to start. A simple spreadsheet with service name, version and owner already solves half the problem.&lt;/p&gt;

&lt;p&gt;And one career note: whoever masters migrating versions safely, without taking production down, will have plenty of work over the coming months. It's not the most exciting part of the profession, but it's the part that holds up the rest.&lt;/p&gt;

&lt;p&gt;Sources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://devblogs.microsoft.com/dotnet/dotnet-8-9-end-of-support/" rel="noopener noreferrer"&gt;Microsoft .NET Blog: .NET 8 and .NET 9 reach end of support on November 10, 2026&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.infoworld.com/article/4191704/end-of-support-looms-for-net-8-and-net-9.html" rel="noopener noreferrer"&gt;InfoWorld: End of support looms for .NET 8 and .NET 9&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://krebsonsecurity.com/2026/11/microsoft-fixes-nearly-1100-security-vulnerabilities/" rel="noopener noreferrer"&gt;Krebs on Security: Microsoft Fixes Nearly 1,100 Security Vulnerabilities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.talosintelligence.com/microsoft-patch-tuesday-for-november-2026" rel="noopener noreferrer"&gt;Cisco Talos: Microsoft Patch Tuesday for November 2026&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.infosecurity-magazine.com/news/microsoft-fixes-1235-flaws-record/" rel="noopener noreferrer"&gt;Infosecurity Magazine: Microsoft Breaks Another Patch Tuesday Record with 1235 Flaws&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>dotnet</category>
      <category>security</category>
      <category>career</category>
      <category>news</category>
    </item>
    <item>
      <title>Cache-aside with FastAPI and Redis: invalidation and concurrent requests</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Wed, 11 Nov 2026 23:37:16 +0000</pubDate>
      <link>https://dev.to/dunirvana/cache-aside-with-fastapi-and-redis-invalidation-and-concurrent-requests-55fg</link>
      <guid>https://dev.to/dunirvana/cache-aside-with-fastapi-and-redis-invalidation-and-concurrent-requests-55fg</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/cache-aside-fastapi-redis.html" rel="noopener noreferrer"&gt;Cache-aside com FastAPI e Redis: invalidação e requisições simultâneas&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Anyone who has put an API in production knows the story: the read endpoint is simple, but the query behind it is expensive, and the same row gets requested hundreds of times per minute. Then someone suggests "put a Redis in front of it". It works, but the hard part isn't writing to the cache. It's deciding when to read, when to invalidate, and what to do when ten requests arrive together and the cache is empty.&lt;/p&gt;

&lt;p&gt;In this post I built a small example with FastAPI and Redis using the cache-aside pattern, paying attention to those two annoying points: invalidation and concurrent requests. Everything runs with docker compose, and the tests don't need a real Redis.&lt;/p&gt;

&lt;h2&gt;
  
  
  The idea: cache-aside
&lt;/h2&gt;

&lt;p&gt;In cache-aside, the application is in charge, not the cache. The read flow is always the same: ask Redis; if it has the value, return it; if not, fetch from the source of truth, store it in Redis with a TTL and return it. On writes, we change the source and delete the cache key, letting the next read repopulate it. It's less clever than write-through, but it's easy to understand and easy to debug.&lt;/p&gt;

&lt;p&gt;In the example, the "database" is a repository that uses &lt;code&gt;asyncio.sleep&lt;/code&gt; to simulate latency and keeps a query counter. That counter is what lets the tests prove the cache is working, instead of trusting a gut feeling.&lt;/p&gt;

&lt;h2&gt;
  
  
  The cached read
&lt;/h2&gt;

&lt;p&gt;The read endpoint is practically the pattern described in code. Notice that the response reports the &lt;code&gt;origem&lt;/code&gt; (origin) of the data, which helps a lot when testing and when watching the behavior with curl.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;em_cache&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;chave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;em_cache&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"origem"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"cache"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"produto"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;loads&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;em_cache&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;produto&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;buscar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;produto&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;HTTPException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;404&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;detail&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"Produto não encontrado"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kt"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;chave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;TTL_SEGUNDOS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"origem"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"banco"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"produto"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;produto&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One detail: a nonexistent product returns 404 and is not cached. You can cache the absence too (negative caching), but then you need a short TTL and care with invalidation when the item starts to exist. For an example, I left it out.&lt;/p&gt;

&lt;h2&gt;
  
  
  The concurrent requests problem
&lt;/h2&gt;

&lt;p&gt;This code has a classic flaw. If the key expires and ten requests arrive at the same time, all ten see an empty cache and all ten hit the database. That's a cache stampede, and it tends to happen at the worst possible moment, under heavy load.&lt;/p&gt;

&lt;p&gt;A simple solution for a single process is a per-key lock. The first request takes the lock and goes to the database; the others wait, and when they get in they check the cache again (the famous double-check), finding the value the first one already stored.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;lock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;locks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setdefault&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;em_cache&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;chave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;em_cache&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"origem"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"cache"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"produto"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;loads&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;em_cache&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="n"&gt;produto&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;buscar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This lock lives in the process memory. With several API instances, each one would make at most one query per key, which already reduces the damage a lot, but doesn't eliminate it. If you need a guarantee across instances, the way to go is a distributed lock in Redis itself (&lt;code&gt;SET key value NX EX&lt;/code&gt;), with the expiration caveats that come with it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Invalidation on write
&lt;/h2&gt;

&lt;p&gt;When the product changes, we delete the key. That's it. The next read goes to the database, gets the new data and repopulates the cache. The TTL still exists as a safety net: if some write forgets to invalidate, the stale data goes away by itself within 30 seconds.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nd"&gt;@app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/produtos/{produto_id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;atualizar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dados&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="no"&gt;PRODUTOS&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="no"&gt;PRODUTOS&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;dados&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;delete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;chave&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="no"&gt;PRODUTOS&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;produto_id&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Testing without Redis
&lt;/h2&gt;

&lt;p&gt;The tests use &lt;code&gt;fakeredis&lt;/code&gt;, which implements the client's async API in memory. Since &lt;code&gt;create_app&lt;/code&gt; receives the client and the repository as parameters, each test builds its own app, with its own counter, and nothing depends on execution order. The most interesting test fires ten parallel requests and checks that there was a single database query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;test_requisicoes_simultaneas_geram_uma_unica_consulta&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;cenario&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;novo_app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;latencia&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nf"&gt;cliente_http&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;respostas&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;gather&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/produtos/1"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"origem"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;respostas&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;consultas&lt;/span&gt;

    &lt;span class="n"&gt;origens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;consultas&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;rodar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;cenario&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;consultas&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;origens&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"banco"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;assert&lt;/span&gt; &lt;span class="n"&gt;origens&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"cache"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The other tests cover the first read coming from the database and the second from the cache, the 404, invalidation after the PUT, and the TTL set on the key.&lt;/p&gt;

&lt;h2&gt;
  
  
  Running with Docker
&lt;/h2&gt;

&lt;p&gt;The compose file brings up the API and a Redis with a healthcheck, and the API only starts after Redis answers the ping. The tests live in a separate service behind a profile, so they don't start together with the application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;services&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;image&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;redis:7-alpine&lt;/span&gt;
    &lt;span class="na"&gt;healthcheck&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;test&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"CMD"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"redis-cli"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"ping"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

  &lt;span class="na"&gt;app&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s"&gt;context:&lt;/span&gt; &lt;span class="s"&gt;.&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;target:&lt;/span&gt; &lt;span class="s"&gt;runtime&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="na"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;REDIS_URL&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;redis://redis:6379/0&lt;/span&gt;
      &lt;span class="na"&gt;CACHE_TTL&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"30"&lt;/span&gt;
    &lt;span class="na"&gt;ports&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"8000:8000"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="na"&gt;depends_on&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;condition&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;service_healthy&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose up --build
curl localhost:8000/produtos/1 &lt;span class="c"&gt;# origem: banco&lt;/span&gt;
curl localhost:8000/produtos/1 &lt;span class="c"&gt;# origem: cache&lt;/span&gt;

docker compose run --rm tests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you repeat the curl after 30 seconds, you'll see the origin go back to &lt;code&gt;banco&lt;/code&gt;, because the TTL expired. And if you do a PUT on the product, the next read also goes back to the database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code
&lt;/h2&gt;

&lt;p&gt;The complete project, with Dockerfile, compose, tests and a CI workflow, is at &lt;a href="https://github.com/dunirvana/programero-python/tree/main/2026-11-cache-aside-fastapi-redis" rel="noopener noreferrer"&gt;programero-python/2026-11-cache-aside-fastapi-redis&lt;/a&gt;. The natural next step is to swap the in-memory lock for a distributed one and measure the difference with several instances.&lt;/p&gt;

</description>
      <category>python</category>
      <category>fastapi</category>
      <category>redis</category>
      <category>docker</category>
    </item>
    <item>
      <title>Black October: AI sped up the hunt for vulnerabilities, and the bill came due</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Sat, 07 Nov 2026 15:59:01 +0000</pubDate>
      <link>https://dev.to/dunirvana/black-october-ai-sped-up-the-hunt-for-vulnerabilities-and-the-bill-came-due-42pj</link>
      <guid>https://dev.to/dunirvana/black-october-ai-sped-up-the-hunt-for-vulnerabilities-and-the-bill-came-due-42pj</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/black-october-ia-e-seguranca.html" rel="noopener noreferrer"&gt;Black October: a IA acelerou a caça às falhas, e a conta chegou&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;October is officially Cybersecurity Awareness Month. In 2026 it earned a much less friendly nickname: &lt;strong&gt;Black October&lt;/strong&gt;. In just a few days we saw a critical PHP flaw discovered with the help of AI, a certificate authority leaving the market because of private keys you could practically guess, and a popular AI library distributing malware through PyPI. If you work with software and didn't have to update anything in the last few weeks, you were either very lucky or didn't look closely.&lt;/p&gt;

&lt;h2&gt;
  
  
  What happened
&lt;/h2&gt;

&lt;p&gt;The loudest episode was &lt;strong&gt;PHP2Shell&lt;/strong&gt;. Researchers at Wiz, with support from OpenAI and Calif, found memory-safety flaws in the PHP core, tied to how the language handles fatal errors, mainly memory exhaustion. A failing request can leave corrupted internal state behind, which another request later reuses. The result is unauthenticated remote code execution, with severity scores up to 9.2. The most striking detail: the problem had been there for more than a decade and affected practically every version since PHP 5.4.&lt;/p&gt;

&lt;p&gt;According to Wiz itself, frontier AI models took part in the discovery, in building the exploits and in validating the patches. The first flaw was found on August 19; within two days there was confirmed remote execution on Drupal and WordPress. PHP shipped the fixes (8.2.35, 8.3.36, 8.4.27 and 8.5.12) on October 21, and the NSA went as far as recommending updating immediately or taking systems offline until you could.&lt;/p&gt;

&lt;p&gt;Almost at the same time came the &lt;strong&gt;eMudhra&lt;/strong&gt; case, an Indian certificate authority. A researcher found that eight private keys for intermediate certificates had values smaller than 256. Yes: keys that should be gigantic random numbers could be recovered almost instantly. Chrome and Firefox blocked the intermediates within hours, Mozilla stopped trusting the affected root, and the company announced it would exit the global TLS certificate business. About 30,000 certificates had to be replaced.&lt;/p&gt;

&lt;p&gt;To close out the week, &lt;strong&gt;LiteLLM&lt;/strong&gt;, a library widely used to talk to multiple language model providers, had its release pipeline compromised. For a few hours on the 21st, version 1.107.0 on PyPI and images on Docker Hub carried a credential stealer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why this matters if you work in tech
&lt;/h2&gt;

&lt;p&gt;None of these cases is new in shape. Old bugs in popular languages, CAs with poor processes and supply chain attacks have all happened before. What changed is the pace. In August, Microsoft's Patch Tuesday fixed 419 vulnerabilities, about five times the volume of a typical month before this wave; in October, the security press counted more than 1,400. Finding flaws got cheaper, and that holds for defenders and attackers alike.&lt;/p&gt;

&lt;p&gt;In practice, a few things become obvious:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Updating is no longer a "when I get around to it" task.&lt;/strong&gt; If the window between disclosure and exploit keeps shrinking, the patch process has to be fast and, ideally, automated.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Inventory is security.&lt;/strong&gt; If you don't know which versions of PHP, Node or Python libraries you run in production, you lose days just figuring out whether you were affected.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pinning versions and verifying package origin matters.&lt;/strong&gt; The LiteLLM case shows that an uncritical automatic update can be the very entry point.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Automatic certificate renewal isn't the end of the story.&lt;/strong&gt; Chrome warned that common ACME clients may not replace certificates outside the renewal window without ARI support or manual intervention.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  My take
&lt;/h2&gt;

&lt;p&gt;A lot of people are treating Black October as proof that AI is going to "break the internet". I see it differently. The PHP flaws had existed for more than ten years; AI didn't create them, it just found them. This is collective technical debt being collected all at once, and it's better for it to be collected by researchers doing coordinated disclosure than by someone working in silence.&lt;/p&gt;

&lt;p&gt;The problem is that the capacity to fix doesn't scale at the same pace as the capacity to find. Open source projects maintained by a handful of people, companies with legacy systems nobody dares to touch, and teams that treat updates as a risk rather than as protection will feel it first. The eMudhra case, by the way, didn't even involve AI: it was a basic process failure, the kind that only shows up when someone finally decides to look.&lt;/p&gt;

&lt;p&gt;For developers, the lesson is less glamorous than it seems: keep dependencies up to date, know what runs in production, have a reliable deploy pipeline and enough tests to update without fear. None of this is new. The difference is that now the bill arrives faster.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sources:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.wiz.io/blog/php2shell-php-rce" rel="noopener noreferrer"&gt;Wiz: PHP2Shell: AI uncovers critical RCE vulnerabilities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://bleepingcomputer.com/news/security/php-ships-emergency-patches-for-critical-php2shell-flaws" rel="noopener noreferrer"&gt;BleepingComputer: PHP ships emergency patches for critical PHP2Shell flaws&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://techcrunch.com/2026/10/21/the-internet-is-having-a-very-bad-cybersecurity-day/" rel="noopener noreferrer"&gt;TechCrunch: The internet is having a very bad cybersecurity day&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://thehackernews.com/2026/10/emudhra-to-exit-global-ssltls-business.html" rel="noopener noreferrer"&gt;The Hacker News: eMudhra to exit global SSL/TLS business&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.litellm.ai/blog/security-incident-oct-21-2026" rel="noopener noreferrer"&gt;LiteLLM: Security incident, Oct 21 2026&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://therecord.media/microsoft-massive-patch-tuesday-releases-continue-ai" rel="noopener noreferrer"&gt;The Record: Microsoft's massive Patch Tuesday releases continue&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.bleepingcomputer.com/news/microsoft/microsoft-october-2026-patch-tuesday-fixes-1-411-flaws-3-zero-days/" rel="noopener noreferrer"&gt;BleepingComputer: Microsoft October 2026 Patch Tuesday fixes 1,411 flaws&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Black_October_(information_security)" rel="noopener noreferrer"&gt;Wikipedia: Black October (information security)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>security</category>
      <category>ai</category>
      <category>php</category>
      <category>news</category>
    </item>
    <item>
      <title>Agents that don't wait for you to ask: the price of privacy and of compute</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Sat, 07 Nov 2026 15:57:32 +0000</pubDate>
      <link>https://dev.to/dunirvana/agents-that-dont-wait-for-you-to-ask-the-price-of-privacy-and-of-compute-13hc</link>
      <guid>https://dev.to/dunirvana/agents-that-dont-wait-for-you-to-ask-the-price-of-privacy-and-of-compute-13hc</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/agentes-sempre-ligados-privacidade-e-custo.html" rel="noopener noreferrer"&gt;Agentes que não esperam você pedir: o preço da privacidade e da computação&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For years, an AI assistant was something that sat waiting for you to type. You ask, it answers, done. The shift happening now is different: agents that stay on all the time, look at your inbox, learn your goals and go off doing things without anyone asking. In theory that's great. In practice, it opens a conversation that those of us working in tech need to have before granting access to everything.&lt;/p&gt;

&lt;h2&gt;
  
  
  What happened
&lt;/h2&gt;

&lt;p&gt;At DevDay on September 29, OpenAI introduced "Dots", agents it describes as always on. Each one has its own cloud computer, with a browser, and connects to thousands of apps through plugins. You can talk to it through ChatGPT or through Slack and Teams, and it runs several projects in parallel. The first Dot is included in the Pro and Business Premium plans, and on the Pro plan the feature hasn't yet reached the European Economic Area, Switzerland and the UK.&lt;/p&gt;

&lt;p&gt;There's a layer of control: rules for when to act alone and when to ask, custom rules to allow, block or require approval for specific actions, and an automatic review before anything that touches accounts or shares information. Changing a password, for example, is still the user's job. OpenAI itself warns that the agent can make mistakes and that all important work needs human review.&lt;/p&gt;

&lt;p&gt;This week, Fortune tied together two threads that usually run separately in this discussion: privacy and the cost of compute.&lt;/p&gt;

&lt;h2&gt;
  
  
  The price of privacy
&lt;/h2&gt;

&lt;p&gt;According to the report, Meredith Whittaker, president of Signal, has been warning that personal agents need deep access to your data to work, and that creates security and privacy risk. The point that struck me most is about consent: whoever sends an email or message to a person using one of these agents never agreed to have an AI read it. The access you grant carries along the correspondence of everyone you talk to.&lt;/p&gt;

&lt;p&gt;OpenAI's own head of developer experience, Romain Huet, suggests gradual trust: start with the calendar and only later open up Slack and Gmail. He says he lets his Dot categorize emails and draft replies, but never send messages on his behalf. It's sensible advice, and it applies to any agent, from any company.&lt;/p&gt;

&lt;h2&gt;
  
  
  The price of compute
&lt;/h2&gt;

&lt;p&gt;An always-on agent costs more than a chatbot. An OpenAI executive admitted that Dots are "compute heavy", and the company already routes part of the work to a smaller model, Terra, which according to OpenAI delivers even better results on some tasks, like computer use and writing, at a tenth of the price. On the side of those paying the bill, Fortune cites Menlo Ventures data: companies spent US$ 177 billion on AI in the 12 months through September, more than five times the previous period, and spent well above what they had budgeted. It also reports that Apple lowered the daily AI spending cap for some engineers from US$ 300 to US$ 200.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why this matters if you work in tech
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Permissions become an architecture decision.&lt;/strong&gt; Whoever integrates agents with internal systems will need to think about least privilege, separate credentials, an audit trail and a way to pause everything. It's the same reasoning as for any service account, except this account now takes initiative.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cost becomes part of the design.&lt;/strong&gt; If the agent runs all day, the token budget stops being an end-of-project detail. Routing between large and small models will likely become common practice.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Privacy is about third parties too.&lt;/strong&gt; In a country with a data protection law like Brazil's LGPD, delegating email and chat reading to an agent means looking at what that implies for clients and colleagues, not just for you.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  My take
&lt;/h2&gt;

&lt;p&gt;I find the idea promising and the moment still immature. The technical side is evolving fast, but usage habits are still in "allow everything and see what happens" mode. I'd treat an agent like this the way I'd treat a very fast intern: start with read access to a few things, approve what it does before it leaves the building, and only expand trust with evidence. And I'd pay attention to what the vendor doesn't answer clearly, especially about what happens to the data of people who aren't your users.&lt;/p&gt;

&lt;p&gt;It's also worth being wary of collective enthusiasm. When the cost is still being subsidized and the access rules change every quarter, any critical process relying on an agent needs a plan B. Use it, yes. Blind dependence, no.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sources:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://fortune.com/2026/11/05/openais-dots-are-coming-up-against-the-price-of-privacy-and-the-price-of-compute" rel="noopener noreferrer"&gt;Fortune - OpenAI's Dots are coming up against the price of privacy, and the price of compute (Nov 5, 2026)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://techcrunch.com/2026/09/29/openai-launches-dots-its-bubbly-agentic-avatar/" rel="noopener noreferrer"&gt;TechCrunch - OpenAI launches dots, its bubbly agentic avatar (Sep 29, 2026)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://thenextweb.com/news/openai-dots-always-on-ai-agents-cloud-computers-devday" rel="noopener noreferrer"&gt;The Next Web - OpenAI launches Dots, always-on AI agents with their own cloud computers&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>privacy</category>
      <category>security</category>
      <category>agents</category>
    </item>
    <item>
      <title>Rate limiting in Minimal APIs with .NET's built-in middleware</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Sat, 07 Nov 2026 15:56:44 +0000</pubDate>
      <link>https://dev.to/dunirvana/rate-limiting-in-minimal-apis-with-nets-built-in-middleware-25mo</link>
      <guid>https://dev.to/dunirvana/rate-limiting-in-minimal-apis-with-nets-built-in-middleware-25mo</guid>
      <description>&lt;p&gt;&lt;em&gt;This post was originally published in Portuguese on my blog: &lt;a href="https://programero.blogspot.com/2026/11/rate-limiting-minimal-apis.html" rel="noopener noreferrer"&gt;Rate limiting em Minimal APIs com o middleware nativo do .NET&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Every API exposed to the internet will, sooner or later, get a client that decides to hit the same endpoint a thousand times per second. It might be a bug in a retry loop, a poorly written script or someone trying their luck. If you have no limit at all, the database, the CPU and your other users pay the bill.&lt;/p&gt;

&lt;p&gt;The good news is that since .NET 7, rate limiting ships with the framework. No extra package, no third-party library. In this post I build a small example with Minimal APIs, per-IP limits, a 429 response with &lt;code&gt;Retry-After&lt;/code&gt; and integration tests.&lt;/p&gt;

&lt;h2&gt;
  
  
  The core idea
&lt;/h2&gt;

&lt;p&gt;The middleware works with two concepts: the &lt;strong&gt;limiter&lt;/strong&gt; (the algorithm: fixed window, sliding window, token bucket or concurrency) and the &lt;strong&gt;partition&lt;/strong&gt; (who is being limited). Without a partition, the limit is global, and one abusive client takes the service down for everyone. Partitioning by IP gives each client its own bucket.&lt;/p&gt;

&lt;p&gt;You register a named policy and then apply it to the endpoints that need it. Endpoints like health checks usually stay out, otherwise the orchestrator may decide your application is down.&lt;/p&gt;

&lt;h2&gt;
  
  
  Registering the policy
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Services&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;AddRateLimiter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;options&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;RejectionStatusCode&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;StatusCodes&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Status429TooManyRequests&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;AddPolicy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"por-ip"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;context&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt;
        &lt;span class="n"&gt;RateLimitPartition&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;GetFixedWindowLimiter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;partitionKey&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Connection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;RemoteIpAddress&lt;/span&gt;&lt;span class="p"&gt;?.&lt;/span&gt;&lt;span class="nf"&gt;ToString&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;??&lt;/span&gt; &lt;span class="s"&gt;"anonimo"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="n"&gt;FixedWindowRateLimiterOptions&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;PermitLimit&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;Window&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;TimeSpan&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;FromSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;windowSeconds&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                &lt;span class="n"&gt;QueueLimit&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;
            &lt;span class="p"&gt;}));&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;QueueLimit = 0&lt;/code&gt; makes excess requests get rejected right away instead of waiting in a queue for the next window. For a public API, that's usually what you want. The limit and window values come from configuration, which helps a lot when testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Telling the client when to come back
&lt;/h2&gt;

&lt;p&gt;Returning 429 without saying when to try again forces the client to guess, and guessing turns into aggressive retries. The &lt;code&gt;OnRejected&lt;/code&gt; callback lets you send back a &lt;code&gt;Retry-After&lt;/code&gt; header with the time left in the window:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;OnRejected&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Lease&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;TryGetMetadata&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;MetadataName&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;RetryAfter&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;out&lt;/span&gt; &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;HttpContext&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Headers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;RetryAfter&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
            &lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;TotalSeconds&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;ToString&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ValueTask&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;CompletedTask&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Applying it to the endpoints
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Build&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;UseRateLimiter&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;MapGet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;Results&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;mensagem&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"ola"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hora&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;DateTime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;UtcNow&lt;/span&gt; &lt;span class="p"&gt;}))&lt;/span&gt;
   &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;RequireRateLimiting&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"por-ip"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;MapGet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/health"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;Results&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"ok"&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; &lt;span class="c1"&gt;// no limit&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Run&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;partial&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Program&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A detail that catches a lot of people: &lt;code&gt;UseRateLimiter()&lt;/code&gt; has to come before mapping the endpoints that use the policy, and the &lt;code&gt;partial class Program&lt;/code&gt; at the end exists only so the test project can see the class.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing it for real
&lt;/h2&gt;

&lt;p&gt;With &lt;code&gt;WebApplicationFactory&lt;/code&gt; you can spin up the application in memory and override the configuration. I lower the limit to 3 requests and keep the window long, so the test doesn't depend on timing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;Fact&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="n"&gt;Task&lt;/span&gt; &lt;span class="nf"&gt;Requisicao_acima_do_limite_retorna_429_com_retry_after&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;_factory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;CreateClient&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="p"&gt;&amp;lt;&lt;/span&gt; &lt;span class="m"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;++)&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;GetAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;resp&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;GetAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;Assert&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;HttpStatusCode&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;TooManyRequests&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;resp&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;StatusCode&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;Assert&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;True&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;resp&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Headers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Retry-After"&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There's also a test making sure &lt;code&gt;/health&lt;/code&gt; handles ten calls in a row without getting a 429. It's the kind of regression that slips by until the day the load balancer pulls your application out of rotation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Running with Docker
&lt;/h2&gt;

&lt;p&gt;The project has a multi-stage Dockerfile with two targets, &lt;code&gt;app&lt;/code&gt; and &lt;code&gt;tests&lt;/code&gt;, and the compose file exposes both:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose up &lt;span class="nt"&gt;--build&lt;/span&gt;
&lt;span class="c"&gt;# in another terminal, call it more than 5 times within 10 seconds&lt;/span&gt;
&lt;span class="k"&gt;for &lt;/span&gt;i &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;seq &lt;/span&gt;1 7&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;do &lt;/span&gt;curl &lt;span class="nt"&gt;-s&lt;/span&gt; &lt;span class="nt"&gt;-o&lt;/span&gt; /dev/null &lt;span class="nt"&gt;-w&lt;/span&gt; &lt;span class="s2"&gt;"%{http_code} "&lt;/span&gt; localhost:8080/&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;done

&lt;/span&gt;docker compose run &lt;span class="nt"&gt;--rm&lt;/span&gt; tests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see something like &lt;code&gt;200 200 200 200 200 429 429&lt;/code&gt;. If you look at the headers of the rejected response, &lt;code&gt;Retry-After&lt;/code&gt; will be there.&lt;/p&gt;

&lt;h2&gt;
  
  
  Before going to production
&lt;/h2&gt;

&lt;p&gt;This limiter lives in the memory of each instance. With several replicas behind a load balancer, each one counts on its own, so the effective limit is multiplied by the number of instances. If you need a global, exact limit, the way to go is a shared counter, usually in Redis, or delegating it to the gateway.&lt;/p&gt;

&lt;p&gt;Behind a reverse proxy, &lt;code&gt;RemoteIpAddress&lt;/code&gt; will be the proxy's IP, not the client's. Configure &lt;code&gt;ForwardedHeaders&lt;/code&gt; first, otherwise all users fall into the same partition and share the same limit.&lt;/p&gt;

&lt;p&gt;For day-to-day work, the built-in middleware handles most basic protection scenarios well, with no dependencies at all.&lt;/p&gt;

&lt;p&gt;The full code is at &lt;a href="https://github.com/dunirvana/programero-csharp/tree/main/2026-11-rate-limiting-minimal-apis" rel="noopener noreferrer"&gt;programero-csharp/2026-11-rate-limiting-minimal-apis&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>aspnetcore</category>
      <category>api</category>
    </item>
    <item>
      <title>Clojure - Símbolos globais e locais</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Fri, 18 Feb 2022 18:20:00 +0000</pubDate>
      <link>https://dev.to/dunirvana/clojure-simbolos-globais-e-locais-482g</link>
      <guid>https://dev.to/dunirvana/clojure-simbolos-globais-e-locais-482g</guid>
      <description>&lt;p&gt;Até agora, sempre que foi necessário manter um valor em memória nós usamos o conceito de "variável", realizando a "definição de um símbolo" com o comando "def". Porém essa abordagem corresponde ao que conhecemos nas linguagens mais tradicionais como "definição de variável global".&lt;/p&gt;

&lt;p&gt;Como é de conhecimento, as definições de "variáveis globais" podem trazer uma série de problemas as aplicações, uma vez que é quase impossível ter conhecimento de todas, com isso podemos acabar gerando problemas com a substituição de valores durante seu uso, podendo causar erros em diversos pontos da aplicação e tornando a aplicação instável e de difícil manutenção.&lt;/p&gt;

&lt;p&gt;Dito isso, veremos como trabalhar com símbolos dentro de um escopo limitado, seguiremos os próximos exemplos dentro de nossas funções.&lt;/p&gt;

&lt;h2&gt;
  
  
  Escopo global
&lt;/h2&gt;

&lt;p&gt;Como vimos até aqui, os símbolos de escopo global podem ser acessados de qualquer parte da aplicação, vamos ao exemplo, considerando uma aplicação hipotética de uma escola, temos duas rotinas distintas que mostram a média dos alunos em duas condições distintas:&lt;/p&gt;

&lt;p&gt;Uma que mostra e média "padrão" acrescida de um ponto extra;&lt;br&gt;
Outra que mostra a média do aluno em uma condição de "recuperação", que acresce a média dois pontos extras;&lt;br&gt;
Enquanto a rotina que mostra a média "padrão" olha para um símbolo global para fazer seu cálculo sem fazer qualquer alteração a rotina que mostra a média dos alunos em condição de "recuperação" também utiliza o mesmo símbolo global, porém ela sempre altera seu valor para "dois".&lt;/p&gt;

&lt;p&gt;O problema que teremos é o seguinte, enquanto a rotina que mostra as médias de alunos em "recuperação" não for executada a rotina de média "padrão", quando executada, apresentará um resultado correto, porém após primeira execução da rotina de "recuperação" a "padrão" começará a mostrar um resultado errado:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(def ponto-extra 1)

(defn verifica-situacao-aluno-padrao
  "Retorna a media do aluno somada a seu ponto extra"
  [nota1 nota2]
  (+ (/ (+ nota1 nota2) 2) ponto-extra)
)
(defn verifica-situacao-aluno-recuperacao
  "Retorna a media do aluno somada a seu ponto extra (em caso de recuperação)"
  [nota1 nota2]
  (def ponto-extra 2)
  (+ (/ (+ nota1 nota2) 2) ponto-extra)
)

ponto-extra
(verifica-situacao-aluno-padrao 5 5)
(verifica-situacao-aluno-recuperacao 5 5)
(verifica-situacao-aluno-padrao 5 5)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faqoy2v7g149g7pywu7md.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faqoy2v7g149g7pywu7md.png" alt="Exemplificando um problema com símbolo global" width="721" height="628"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Sobre a imagem:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na linha três definimos nosso símbolo global "ponto-extra";&lt;/li&gt;
&lt;li&gt;Da linha cinco até a linha dezesseis definimos nossas duas funções, "padrão" e "recuperação" respectivamente;&lt;/li&gt;
&lt;li&gt;Na linha dezenove checamos o valor do nosso símbolo global "ponto-extra", que é "1";&lt;/li&gt;
&lt;li&gt;Na linha vinte e um consultamos a situação de um aluno com a rotina "padrão" e vemos que sua média é "6";&lt;/li&gt;
&lt;li&gt;Na linha vinte e três consultamos a situação de um aluno com a rotina de "recuperação" e vemos que sua média é "7";&lt;/li&gt;
&lt;li&gt;Na linha vinte e cinco consultamos a situação de um aluno com a rotina "padrão" novamente e agora vemos um resultado diferente, sua média passou a ser "7", mesmo valor que a rotina de "recuperação";&lt;/li&gt;
&lt;li&gt;Na linha vinte e sete checamos o valor do nosso símbolo global "ponto-extra" novamente, e conforme esperado ele agora é "2";&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Conforme já explicado, a função de "recuperação" altera o valor do símbolo global que é usado por outras funções, essa mudança não era esperada em outras partes da aplicação e isso gerou um problema de divergência de valores, e pior, a momentos onde o problema não ocorre (já que ele só ocorre a partir da primeira execução da rotina de "recuperação") e a rotinas que continuam a funcionar (a rotina "recuperação" sempre funciona). Acabamos de gerar um bug em nossa aplicação que não será nada fácil de simular/encontrar/corrigir.&lt;/p&gt;

&lt;h2&gt;
  
  
  Escopo local
&lt;/h2&gt;

&lt;p&gt;Como visto anteriormente, o uso inadequado de um símbolo global gerou um bug em nossa aplicação, para resolver esse problema o desenvolvedor que criou a função de "recuperação" deveria ter usado um símbolo de escopo local na rotina, uma vez que o valor de "ponto-extra" usado ali é uma regra especifica dessa rotina.&lt;/p&gt;

&lt;p&gt;Para trabalharmos com o escopo local utilizaremos a função "let", com ele criamos um escopo local com símbolos e funções:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;O "let" deve ser usado entre parênteses;&lt;/li&gt;
&lt;li&gt;Ele recebe um vetor de símbolos/valores;&lt;/li&gt;
&lt;li&gt;Ele recebe uma ou mais funções;&lt;/li&gt;
&lt;li&gt;Ele retorna o resultado da execução de sua última função;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(let [idade 40] (+ idade 1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fafdrv4w30zcz3u5m4xuw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fafdrv4w30zcz3u5m4xuw.png" alt="Usando o let pela primeira vez" width="432" height="122"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Na imagem acima:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na linha um criamos nosso escopo local com o "let", nesse escopo temos o símbolo "idade" com o valor "40" dentro do vetor e temos uma função que soma a valor "1" ao nosso símbolo "idade";&lt;/li&gt;
&lt;li&gt;Na linha dois temos o resultado da função de soma;&lt;/li&gt;
&lt;li&gt;Na linha três tentamos usar o símbolo "idade" e recebemos um erro na sequencia dizendo que não foi possível resolver o símbolo;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bom, agora que já sabemos como resolver o problema de escopo vamos aplicar uma correção em nossa função "recuperação", para que ela deixe de usar o símbolo global, primeiro vamos reiniciar o símbolo global para seu valor correto, em seguida vamos corrigir a função e ne sequencia executar os testes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(def ponto-extra 1)

(defn verifica-situacao-aluno-recuperacao
  "Retorna a media do aluno somada a seu ponto extra (em caso de recuperação)"
  [nota1 nota2]
  (let [ponto-extra-recuperacao 2]
    (+ (/ (+ nota1 nota2) 2) ponto-extra-recuperacao))  
)

(verifica-situacao-aluno-padrao 5 5)
(verifica-situacao-aluno-recuperacao 5 5)
(verifica-situacao-aluno-padrao 5 5)
ponto-extra
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4i6ciqsv6lfc67tzkfu5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4i6ciqsv6lfc67tzkfu5.png" alt="Refatorando a função para uso do escopo local" width="708" height="357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Na imagem acima:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na linha 1 redefinimos nosso símbolo global para seu valor correto;&lt;/li&gt;
&lt;li&gt;Da linha três até a oito temos a refatoração de nossa função com o uso do "let";&lt;/li&gt;
&lt;li&gt;Nas linhas dez, doze e catorze repetimos os testes, e agora os seus respectivos resultados estão corretos;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;Nesse post entendemos e exemplificamos os problemas causados pelo uso do escopo global, vimos como trabalhar com escopo local com o "let" e refatoramos nossa função problemática para que nossa aplicação voltasse a funcionar da forma esperada.&lt;/p&gt;

&lt;h2&gt;
  
  
  Saiba mais
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://clojure.org/" rel="noopener noreferrer"&gt;Clojure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://clojure.org/about/functional_programming" rel="noopener noreferrer"&gt;Functional Programming&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://programero.blogspot.com/2022/02/clojure-simbolos-globais-e-locais.html" rel="noopener noreferrer"&gt;Escrito originalmente aqui&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>clojure</category>
      <category>functional</category>
      <category>braziliandevs</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Clojure - Criando nossa primeira função</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Wed, 09 Feb 2022 17:26:29 +0000</pubDate>
      <link>https://dev.to/dunirvana/clojure-criando-nossa-primeira-funcao-1cdj</link>
      <guid>https://dev.to/dunirvana/clojure-criando-nossa-primeira-funcao-1cdj</guid>
      <description>&lt;p&gt;Anteriormente vimos como configurar o ambiente e em seguida escrevemos nossas primeiras linhas de código para começarmos a entender como o Clojure funciona, usamos algumas funções "nativas", declaramos algumas "variáveis" e também brincamos com um vetor.&lt;/p&gt;

&lt;p&gt;Nesse post daremos mais um passo, escreveremos nossa primeira função, passando por algumas de suas características e entendendo um pouco sobre como a criação delas funciona.&lt;/p&gt;

&lt;h2&gt;
  
  
  Definindo nossa primeira função
&lt;/h2&gt;

&lt;p&gt;Para criar nossa primeira função precisamos ter em mente que o que deve ser feito é algo semelhante a definição de uma variável, a diferença fica por conta do uso do comando "defn" (é possível usar o "def", mas veremos isso futuramente), basicamente precisaremos:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Escrever todo o conteúdo dentro de parênteses;&lt;/li&gt;
&lt;li&gt;Usar o comando "defn";&lt;/li&gt;
&lt;li&gt;Definir uma lista de parâmetros, se não existirem parâmetros (nosso caso agora) essa lista deve estar vazia;&lt;/li&gt;
&lt;li&gt;Definir o corpo da função;&lt;/li&gt;
&lt;li&gt;Opcionalmente podemos colocar um comentário para deixar mais claro o que a função faz;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Definindo nossa função:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(defn minha-primeira-funcao
  "Exemplo de uma função"
  []
  (println "Minha primeira função!")
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Executando nossa função:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(minha-primeira-funcao)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftwyra48854iybxuxa8ci.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftwyra48854iybxuxa8ci.png" alt="Criando nossa primeira função!" width="343" height="287"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Na imagem acima temos:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na linha três temos o inicio da definição de nossa função com o uso de "defn" seguido do nome que escolhemos;&lt;/li&gt;
&lt;li&gt;Na linha quatro, entre aspas duplas, temos o comentário que explica o que a função faz;&lt;/li&gt;
&lt;li&gt;Na linha cinco temos o vetor de parâmetros vazio;&lt;/li&gt;
&lt;li&gt;Na linha seis temos o corpo de nossa função, que realiza a impressão no console de uma frase;&lt;/li&gt;
&lt;li&gt;Na linha sete temos o fechamento de nossa função;&lt;/li&gt;
&lt;li&gt;Na linha nove executamos a nossa função;&lt;/li&gt;
&lt;li&gt;Na linha dez temos o resultado da execução e na onze o retorno;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Apenas um detalhe, a função toda foi escrita no bloco de notas, e depois copiada para o console para a execução.&lt;/p&gt;

&lt;h2&gt;
  
  
  Criando uma função que recebe parâmetros e devolve um valor
&lt;/h2&gt;

&lt;p&gt;De acordo com nosso exemplo anterior, para criarmos uma função que receba parâmetros basta declara-los no vetor que tem essa responsabilidade, agora para retornar um valor basta construirmos uma instrução que retorne um valor.&lt;/p&gt;

&lt;p&gt;Para nosso segundo exemplo criaremos uma função que calculará e retornará a média de um aluno com base em duas notas:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(defn calcula-media
  "Calculando a media de duas notas"
  [nota1, nota2]
  (/ (+ nota1 nota2) 2)
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Executando nossa segunda função:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(calcula-media 7M 8M)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmoghpasrl4jqhd68whv6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmoghpasrl4jqhd68whv6.png" alt="Função que calcula a média de duas notas" width="348" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Na imagem acima temos:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Da linha três a linha sete temos a definição de nossa função, destaque para a linha cinco onde temos a definição de dois parâmetros (nossas duas notas) e para a linha seis, onde de fato realizamos o cálculo e por consequência o retorno da média, analisando de "dentro" para "fora" temos a soma das notas e depois a divisão por dois;&lt;/li&gt;
&lt;li&gt;Na linha nove temos a execução da função de média, onde informamos as duas notas, a "letra M" colocada junto do valor das notas é apenas para termos um resultado mais amigável, a frente entenderemos melhor a questão de tipos de dados;&lt;/li&gt;
&lt;li&gt;E na linha dez temos o resultado apresentado, a média calculada;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;Nesse post escrevemos nossas duas primeiras funções e entendemos como passar parâmetros e devolver um resultado.&lt;/p&gt;

&lt;h2&gt;
  
  
  Saiba mais
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://clojure.org/" rel="noopener noreferrer"&gt;Clojure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://clojure.org/guides/learn/functions" rel="noopener noreferrer"&gt;Learn Clojure - Functions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://programero.blogspot.com/2022/02/clojure-criando-nossa-primeira-funcao.html" rel="noopener noreferrer"&gt;Escrito originalmente aqui&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>clojure</category>
      <category>functional</category>
      <category>beginners</category>
      <category>braziliandevs</category>
    </item>
    <item>
      <title>Clojure - Funções, vetores e def</title>
      <dc:creator>Eduardo Teixeira</dc:creator>
      <pubDate>Mon, 07 Feb 2022 12:28:47 +0000</pubDate>
      <link>https://dev.to/dunirvana/clojure-funcoes-vetores-e-def-4133</link>
      <guid>https://dev.to/dunirvana/clojure-funcoes-vetores-e-def-4133</guid>
      <description>&lt;p&gt;Nessa postagem escreveremos nossas primeiras linhas de código com o Clojure, aqui tentaremos trazer alguns conceitos para mais perto de quem já programa com os paradigmas mais tradicionais (orientação a objetos por exemplo), de modo que fique mais simples entender as intenções e começarmos a correlacionar alguns pontos, mesmo que alguns deles não sejam necessariamente a mesma coisa.&lt;/p&gt;

&lt;h2&gt;
  
  
  Funções
&lt;/h2&gt;

&lt;p&gt;Como já é de conhecimento, funções são pequenas partes de um programa que executam um trabalho e devolvem um resultado, e para que esse trabalho seja realizado muitas vezes é necessário informar argumentos ou informações para que algo seja feito.&lt;/p&gt;

&lt;p&gt;Em Clojure toda invocação de uma função ocorre dentro de parênteses, logo podemos interpretar o conteúdo que esta dentro dos parênteses da seguinte forma:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;O primeiro valor é a função a ser executada;&lt;/li&gt;
&lt;li&gt;O segundo valor é o primeiro argumento que a função receberá;&lt;/li&gt;
&lt;li&gt;Vamos agora ao nosso primeiro exemplo, iremos chamar uma função que escreve no console, passando como "argumento" o famoso "Olá Mundo!":
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(println "Olá Mundo!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzoybd0a23qqi37z2r7ob.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzoybd0a23qqi37z2r7ob.png" alt="Nosso primeiro comando!" width="360" height="174"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Vamos falar sobre a imagem agora, linha por linha:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na primeira linha estamos iniciando o Clojure com o comando "clj";&lt;/li&gt;
&lt;li&gt;Na segunda linha nos é apresentada a versão atual (1.10.3);&lt;/li&gt;
&lt;li&gt;Na terceira linha começamos a escrever nosso primeiro código, chamando a função "println";&lt;/li&gt;
&lt;li&gt;Na quarta linha temos o resultado da execução interna da função "println", que é a escrita no console da frase que informamos como "argumento";&lt;/li&gt;
&lt;li&gt;Na quinta linha temos o retorno da função "println", como ela não retorna nada recebemos nulo (nil);&lt;/li&gt;
&lt;li&gt;Na sexta e última linha temos o controle a disposição novamente para informar os próximos comandos;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ainda sobre funções vale destacar que os operadores matemáticos também são considerados como funções, logo se quisermos somar dois números, por exemplo, precisaríamos iniciar a expressão com o operador de soma, seguido dos "argumentos" (números) que desejamos somar:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(+ 1 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Iniciar a a expressão com um número, utilizando um padrão de operação comum nas linguagens  de programação mais tradicionais resultaria em erro, uma vez que o Clojure tentaria interpretar um número como uma função:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(1 + 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fczx95bmspq1oeyau1pfq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fczx95bmspq1oeyau1pfq.png" alt="Somando dois números" width="550" height="152"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Na imagem acima vemos os dois exemplos, o primeiro com o resultado correto, onde a soma é o primeiro parâmetro e o segundo com o resultado incorreto, onde o Clojure nos diz que o número informado não é uma função.&lt;/p&gt;

&lt;h2&gt;
  
  
  def
&lt;/h2&gt;

&lt;p&gt;Quando estamos programando é trivial mantermos determinados valores (independente do tipo) armazenados em memória, para podermos acessá-los durante a execução de uma aplicação ou função e comumente realizamos isso por meio de "variáveis", sendo justamente esse o conceito que utilizaremos agora para tentar entender o "def".&lt;/p&gt;

&lt;p&gt;Com o "def" criamos (ou definimos) símbolos que nos permitem salvar e recuperar determinados valores, funcionando de forma semelhante a uma variável, sua sintaxe é simples, e funciona como uma função, onde temos a função propriamente dita, o símbolo a ser criado/atualizado e o valor que pretendemos associar ao símbolo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(def total-de-alunos 25)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Para poder ver o valor armazenado em nosso símbolo podemos usar o "println" ou podemos ver seu conteúdo simplesmente digitando o nome do símbolo (fora de parentes é claro):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(println total-de-alunos)

total-de-alunos
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkuvox0l2zeuj1gmj3v4t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkuvox0l2zeuj1gmj3v4t.png" alt="Definindo um símbolo e vendo seu conteúdo" width="391" height="247"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Na imagem acima vemos o seguinte:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na linha três a definição do símbolo "total-de-alunos" com o valor "25";&lt;/li&gt;
&lt;li&gt;Na linha quatro o retorno que nos indica o espaço onde nosso símbolo esta gravado (user);&lt;/li&gt;
&lt;li&gt;Na linha cinco executamos a função "println" para ver o conteúdo;&lt;/li&gt;
&lt;li&gt;Na linha oito verificamos o valor do símbolo diretamente, sem o uso de uma função;&lt;/li&gt;
&lt;li&gt;Nas linhas seis e nove podemos ver o valor armazenado no símbolo;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Para alterar o valor de um símbolo basta utilizarmos o "def" novamente, informando o identificador e o novo valor, esse novo valor pode ser um número fixo (como vimos anteriormente) ou pode ser a execução de uma outra função:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(def total-de-alunos 30)

(def total-de-alunos (+ total-de-alunos 5))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi7jjna7mxcr2770r0c0d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi7jjna7mxcr2770r0c0d.png" alt="Alterando o valor do símbolo" width="461" height="193"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Podemos observar na imagem acima:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na linha um definimos um novo valor para o símbolo;&lt;/li&gt;
&lt;li&gt;Na linha três pedimos para ver o novo valor e na linha quatro o vemos (30);&lt;/li&gt;
&lt;li&gt;Na linha cinco alteramos o valor novamente, fazendo com que o novo valor seja o valor já existente "30" somado a "5";&lt;/li&gt;
&lt;li&gt;Na linha sete pedimos para ver o novo valor e na linha oito o vemos (35);&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Vetores
&lt;/h2&gt;

&lt;p&gt;Quando começamos a aprender uma nova linguagem de programação umas das primeiras estruturas que aprendemos para armazenar uma série de elementos é o vetor, em Clojure não é diferente, a exemplo do que vimos anteriormente, iremos usar o "def" para definir um símbolo ficando por conta do valor atribuído a definição desse vetor, em nosso caso iremos atribuir uma série de nomes entre colchetes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(def alunos ["Maria", "Flávia", "Teresa"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Perceba que no comando acima utilizamos "virgulas" para separar os elementos, mas o que conta mesmo para essa separação são os espaços, a virgula esta ali apenas como uma boa prática que nos permite identificar melhor os itens (inclusive as virgulas são consideradas como espaços no Clojure).&lt;/p&gt;

&lt;p&gt;Para ver os itens de nosso vetor podemos usar tanto as formas já vistas até aqui, com o "println" ou digitando o nome do símbolo diretamente, o que resulta na apresentação de todos os valores ou podemos acessá-los por meio de suas posições, nesse último caso o vetor acaba funcionando como uma função que recebe como parâmetro a posição desejada:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(println alunos)

alunos

(alunos 2)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F22c8jzvj67uhnwlwoukw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F22c8jzvj67uhnwlwoukw.png" alt="Criando o vetor e vendo seu conteúdo" width="468" height="297"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Quando trabalhamos com vetor temos a disposição a função "count" para contar o total de elementos:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(count alunos)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Agora se nossa intenção for adicionar um novo item ao vetor devemos usar a função "conj", aqui é muito importante entendermos que essa função não altera o vetor original, o que ela faz é retornar um novo vetor que possui os valores anteriores e também o novo, isso devido a imutabilidade do Clojure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(conj alunos "Eduardo")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mas qual a vantagem da imutabilidade então? Bom ela nos garante que nossa informação (no caso os valores de nosso vetor) não serão alterados sem o nosso conhecimento ao utilizarmos outras funções, desse modo temos uma confiabilidade maior sobre a informação uma vez que ela só será alterada se realmente desejarmos, ou seja, não corremos o risco de termos os dados alterados por uma função que se quer conhecemos a implementação.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzzh6xf6ra2aenquubi6c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzzh6xf6ra2aenquubi6c.png" alt="Adicionando valor ao vetor sem alterá-lo" width="462" height="271"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Na imagem acima temos:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Na linha sete usamos a função "conj" para adicionar um elemento ao vetor;&lt;/li&gt;
&lt;li&gt;Na linha oito a função "conj" nos retorna o novo vetor contendo a alteração que realizamos;&lt;/li&gt;
&lt;li&gt;Na linha nove e dez podemos perceber que o vetor original "alunos" não foi alterado;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Certo, como já é possível imaginar, se nossa intenção for alterar o vetor original precisaremos então redefinir o valor do nosso símbolo "vetor", sendo que seu novo valor será o resultado da execução da função "conj":&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(def alunos (conj alunos "Eduardo"))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy1a4oayui1byvbaf11vh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy1a4oayui1byvbaf11vh.png" alt="Novo valor no vetor original" width="397" height="97"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Como podemos ver na imagem acima agora o vetor original "alunos" possui o novo valor.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;Nessa postagem sentimos o gostinho inicial do Clojure, escrevemos nosso primeiro "Olá Mundo!", definimos nossa primeira "variável" e criamos nosso primeiro vetor. Também nos deparamos com a imutabilidade, entendendo como ela funciona e uma de suas principais vantagens.&lt;/p&gt;

&lt;h2&gt;
  
  
  Saiba mais
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://clojure.org/" rel="noopener noreferrer"&gt;Clojure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://clojure.org/guides/learn/syntax" rel="noopener noreferrer"&gt;Learn Clojure - Syntax&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://programero.blogspot.com/2022/02/clojure-funcoes-vetores-e-def.html" rel="noopener noreferrer"&gt;Escrito originalmente aqui&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>clojure</category>
      <category>functional</category>
      <category>beginners</category>
      <category>braziliandevs</category>
    </item>
  </channel>
</rss>
