<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[celery.school]]></title><description><![CDATA[Hey there 👋, I'm Bjoern, and I share what I've learned from building a B2B product that relies on Celery, the Python task queue 💪.]]></description><link>https://celery.school</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1700479714533/aGIvoWQDg.png</url><title>celery.school</title><link>https://celery.school</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 13:49:47 GMT</lastBuildDate><atom:link href="https://celery.school/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Happy User, Happy Life: Real-Time Celery Progress Bars With FastAPI and HTMX]]></title><description><![CDATA[How to build real-time progress bars for long running Celery tasks using FastAPI and HTMX]]></description><link>https://celery.school/celery-progress-bars-with-fastapi-htmx</link><guid isPermaLink="true">https://celery.school/celery-progress-bars-with-fastapi-htmx</guid><category><![CDATA[FastAPI]]></category><category><![CDATA[celery]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[htmx]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Tue, 16 Jan 2024 22:39:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705427716165/70a3cf08-45da-4d2c-a8bb-b93584c8ed41.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Imagine this: You are interacting with a web app where you upload an Excel workbook. When the upload is finished, the app lets you browse the workbook content, its version history and shows you the diffs between versions.</p>
<p>Deep down in the engine room, invisible to you, some heavy lifting is required between the “finished uploading” and the “I can do stuff” part. The workbook needs to be serialised. This can take anything from a few seconds to a couple of minutes.</p>
<p>And that’s a frustrating user experience if you, as the user, have no idea how much longer you have to wait before you can navigate and explore the workbook you’ve just uploaded.</p>
<p>This was the case with the app where I am the technical partner. Until recently, we would indicate that something’s happening in the background by showing the user a “processing” status badge without any further information.</p>
<p>We’ve created a much better user experience now, showing a progress bar which tracks the status of the Celery task. Delivering real-time updates from deep down in the engine room to the user’s browser.</p>
<p>In this article, I’m going to explain how we did it and how you can use the same concept to create a great user experience when dealing with long running Celery tasks.</p>
<p>The stack I’m using in this article:</p>
<ul>
<li><p>Celery</p>
</li>
<li><p>FastAPI</p>
</li>
<li><p>server-side rendering with Jinja2 templates</p>
</li>
<li><p>htmx to partially update the HTML</p>
</li>
<li><p>Redis as a message broker and pub/sub backend</p>
</li>
</ul>
<p>With a few adaptions you can use the same concept if you are using Django, Flask or other web frameworks. The underlying concept is independent of the framework you are using.</p>
<h2 id="heading-measure-progress-in-celery-tasks">Measure Progress in Celery Tasks</h2>
<p>The first step is to measure progress inside your Celery task. Progress is 0 at the beginning and 1 at the end of the task.</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.task</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">task</span>():</span>
    <span class="hljs-comment"># start</span>
    progress = <span class="hljs-number">0</span>
    ...
    progress = <span class="hljs-number">1</span>
    <span class="hljs-comment"># end</span>
</code></pre>
<p>In my case, the Celery task traverses a loop with a known number of iterations:</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.task</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">task</span>():</span>
    progress = <span class="hljs-number">0</span>
    n = <span class="hljs-number">100</span>
    progress_step = <span class="hljs-number">1</span>/n
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(n):
        ...
        progress += <span class="hljs-number">1</span>/n
</code></pre>
<p>Now, instead of being stuck at 0 and then jumping to 1, progress is more granular. It isn’t necessarily linear in time though. For example, one step can take half a second and the next can take 30 seconds. It still gives a correct indication of progress. As long as you can break your task into multiple steps, you are able to quantify progress.</p>
<h2 id="heading-record-progress">Record Progress</h2>
<p>Ultimately, our goal is to make this progress information available to the user. This means, it needs to be available to the web server process. So we need to persist it somewhere, for example a database. To keep things simple for this article, I use Redis and write progress to the “progress” key:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> redis

...
db = redis.from_url(<span class="hljs-string">"redis://localhost:6379/1"</span>)
...

<span class="hljs-meta">@app.task</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">task</span>():</span>
    progress = <span class="hljs-number">0</span>
    n = <span class="hljs-number">100</span>
    progress_step = <span class="hljs-number">1</span>/n
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(n):
        ...
        progress += <span class="hljs-number">1</span>/n
        db.set(“progress”, progress)
</code></pre>
<h2 id="heading-user-interface">User Interface</h2>
<p>By now, we have a Celery task that measures and records progress in real-time. I am now turning our attention to the user interface, where we want to show the recorded task progress as a progress bar. I use FastAPI as my web framework and my FastAPI app does three things:</p>
<ul>
<li><p>serve <code>index.html</code> (<code>GET /</code>)</p>
</li>
<li><p>get the current progress from Redis and serve the progress bar as an html snippet (<code>GET /progress</code>)</p>
</li>
<li><p>start the Celery task (<code>POST /start</code>)</p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI, Request
<span class="hljs-keyword">from</span> fastapi.templating <span class="hljs-keyword">import</span> Jinja2Templates
<span class="hljs-keyword">from</span> worker <span class="hljs-keyword">import</span> task
<span class="hljs-keyword">import</span> redis

fastapi_app = FastAPI()
templates = Jinja2Templates(directory=<span class="hljs-string">"templates"</span>)
db = redis.from_url(<span class="hljs-string">"redis://localhost:6379/1"</span>, decode_responses=<span class="hljs-literal">True</span>)

<span class="hljs-meta">@fastapi_app.get("/")</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>(<span class="hljs-params">request: Request</span>):</span>
    <span class="hljs-keyword">return</span> templates.TemplateResponse(
        <span class="hljs-string">"index.html"</span>, {<span class="hljs-string">"request"</span>: request}
    )


<span class="hljs-meta">@fastapi_app.get("/progress")</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">progress</span>(<span class="hljs-params">request: Request</span>):</span>
    progress = <span class="hljs-number">100</span> * float(db.get(<span class="hljs-string">"progress"</span>) <span class="hljs-keyword">or</span> <span class="hljs-number">0</span>)
    <span class="hljs-keyword">return</span> templates.TemplateResponse(
        <span class="hljs-string">"partials/progressbar.html"</span>, {<span class="hljs-string">"request"</span>: request, <span class="hljs-string">"progress"</span>: progress}
    )

<span class="hljs-meta">@fastapi_app.post("/start")</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">start</span>(<span class="hljs-params">request: Request</span>):</span>
    db.set(<span class="hljs-string">"progress"</span>, <span class="hljs-number">0</span>)
    task.s().apply_async()
</code></pre>
<p>Start the FastAPI app via uvicorn:</p>
<pre><code class="lang-python">uvicorn main:fastapi_app --reload --port=<span class="hljs-number">8000</span>
</code></pre>
<h2 id="heading-htmx">htmx</h2>
<p>I use htmx to give me access to modern browser features directly from HTML, rather than using javascript. htmx is probably the most exciting, and boring, frontend tech I’ve seen in a while. I like boring because it implies simplicity.</p>
<p>With htmx, the server responds with HTML and not JSON. This allows you to directly swap out html elements, without having to deal with client-side models and renderers.</p>
<p>The FastAPI app serves <code>index.html</code> on its root. <code>index.html</code> is a simple html page that loads the bootstrap and htmx libraries and provides some simple html layout. It also comes with a start button that uses htmx to send a POST request to <code>/start</code> and instructs it to do nothing with the server response via the <code>hx-swap: "none"</code> attribute.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary"</span> <span class="hljs-attr">hx-post</span>=<span class="hljs-string">"/start"</span> <span class="hljs-attr">hx-swap</span>=<span class="hljs-string">"none"</span>&gt;</span>Start<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<h2 id="heading-progress-bar">Progress Bar</h2>
<p>When you load the page in your browser for the first time, you will see an empty progress bar.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705429463919/d6b4f7f4-2416-4d2a-99f6-a89d83ec5b3a.png" alt class="image--center mx-auto" /></p>
<p>Interestingly, there is no trace of the actual progress bar in <code>index.html</code>, only the progress bar’s outer div.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mb-4"</span>&gt;</span>Progress Bar<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
  <span class="hljs-attr">class</span>=<span class="hljs-string">"progress"</span> 
  <span class="hljs-attr">role</span>=<span class="hljs-string">"progressbar"</span> 
  <span class="hljs-attr">hx-get</span>=<span class="hljs-string">"/progress"</span>
  <span class="hljs-attr">hx-trigger</span>=<span class="hljs-string">"load"</span>,
  <span class="hljs-attr">hx-target</span>=<span class="hljs-string">"this"</span>
  <span class="hljs-attr">hx-swap</span>=<span class="hljs-string">"innerHTML"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>How does this work? On page load, the htmx instruction <code>hx-trigger="load"</code> in combination with <code>hx-get="/progress"</code>makes htmx send a GET request to <code>/progress</code>. The server responds with the html snippet for the progress bar and htmx replaces the inner html of the div because of <code>hx-swap="innerHTML"</code>. When the page loads and no progress has been recorded, the <code>/progress</code> endpoint returns:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"progress-bar"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"width: 0%"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>htmx swaps this for the previosuly empty inner div, so that the rendered html now looks like this:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mb-4"</span>&gt;</span>Progress Bar<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
  <span class="hljs-attr">class</span>=<span class="hljs-string">"progress"</span> 
  <span class="hljs-attr">role</span>=<span class="hljs-string">"progressbar"</span> 
  <span class="hljs-attr">hx-get</span>=<span class="hljs-string">"/progress"</span>
  <span class="hljs-attr">hx-trigger</span>=<span class="hljs-string">"load"</span>,
  <span class="hljs-attr">hx-target</span>=<span class="hljs-string">"this"</span>
  <span class="hljs-attr">hx-swap</span>=<span class="hljs-string">"innerHTML"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"progress-bar"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"width: 0%"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h1 id="heading-real-time-progress-bar-updates">Real-time Progress Bar Updates</h1>
<p>So far we have:</p>
<ul>
<li><p>a Celery task that calculates its own progress and writes it to Redis</p>
</li>
<li><p>a FastAPI controller that reads the task progress from Redis and returns it as a progress bar HTML snippet</p>
</li>
<li><p>an HTML page that loads the progress bar via htmx</p>
</li>
<li><p>and a button to kick off the Celery task</p>
</li>
</ul>
<p>With this, we can start the long-running Celery task via the start button and track its progress. Unfortunately, the only way to refresh the progress bar is to manually reload the browser.</p>
<p>What we are missing for a self-updating, real-time progress bar are server-side triggered events. Similar to <code>hx-trigger="load"</code>, we need the Celery task to trigger an event that makes the UI reload the progress bar.</p>
<h1 id="heading-socketio-server">socket.io Server</h1>
<p>socket.io enables real-time communication between a web browser and a server. We do already have a communication link between the browser and the FastAPI app, we need to figure out how to</p>
<ul>
<li><p>establish a socket.io connection between the web server and the browser</p>
</li>
<li><p>how to get the Celery task to notify the web server of an update</p>
</li>
<li><p>how to get the web server relay the event to the browser</p>
</li>
</ul>
<p>Let’s start with the socket.io connection between the browser and the web server. Up until now, we only had a FastAPI process running via uvicorn. For this two-way communication between server and browser, we also need a socket.io process:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> socketio

<span class="hljs-comment"># socketio</span>
socketio_server = socketio.AsyncServer(async_mode=<span class="hljs-string">"asgi"</span>)

<span class="hljs-comment"># fastapi</span>
fastapi_app = FastAPI()

<span class="hljs-comment"># socketio + fastapi app</span>
socketio_app = socketio.ASGIApp(
    socketio_server=socketio_server,
    other_asgi_app=fastapi_app)
</code></pre>
<p>Instead of uvicorn running <code>fastapi_app</code>, we will have it running <code>socketio_app</code>.</p>
<pre><code class="lang-bash">uvicorn main:socketio_app --reload --port=8000
</code></pre>
<p><code>socketio_app</code> dispatches socket.io-related traffic to <code>socketio_server</code> ("socketio_server") and forwards unrelated HTTP traffic to <code>fastapi_app</code> ("other_asgi_app").</p>
<h2 id="heading-socketio-client">socket.io Client</h2>
<p>Client-side, I use <code>htmx.trigger</code> to bridge incoming socket.io to events, that htmx can act on.</p>
<pre><code class="lang-javascript">&lt;script&gt;
    <span class="hljs-keyword">var</span> socket = io();
    socket.on(<span class="hljs-string">"trigger-event"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        htmx.trigger(<span class="hljs-built_in">document</span>.body, data.event);
    });
&lt;/script&gt;
</code></pre>
<p>Here, I tell the socket.io client to listen for <code>trigger-event</code> events - that come with a payload <code>event</code> property - and use that to trigger an event on the HTML document's body element.</p>
<p>Why am I doing this? Remember how the progress bar is loaded into the inner div on page load, using the <code>hx-trigger="load"</code> attribute? And how we want to do the same - trigger a reload of the progress bar - on task progress updates? Imagine the socket.io client receives an event like this:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"trigger-event"</span>, {<span class="hljs-string">"event"</span>: <span class="hljs-string">"progress"</span>}
</code></pre>
<p>If we now extend the<code>hx-trigger</code> to also react to the <code>progress</code> event from the <code>body</code> element like so</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mb-4"</span>&gt;</span>Progress Bar<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
  <span class="hljs-attr">class</span>=<span class="hljs-string">"progress"</span> 
  <span class="hljs-attr">role</span>=<span class="hljs-string">"progressbar"</span> 
  <span class="hljs-attr">hx-get</span>=<span class="hljs-string">"/progress"</span>
  <span class="hljs-attr">hx-trigger</span>=<span class="hljs-string">"load, progress from:body"</span>,
  <span class="hljs-attr">hx-target</span>=<span class="hljs-string">"this"</span>
  <span class="hljs-attr">hx-swap</span>=<span class="hljs-string">"innerHTML"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>we will have achieved exactly that: a reload of the progress bar.</p>
<h2 id="heading-emit-events-from-celery">Emit events from Celery</h2>
<p>The last missing piece in the puzzle is emitting the <code>trigger-event, {"event": "progress"}</code>event from Celery. socket.io comes with support for Redis for event sharing across multiple processes via Redis Pub/Sub mechanism via <code>socketio.RedisManager</code>. This breaks the problem down into two:</p>
<ul>
<li><p>emit an event via Redis Pub/Sub from Celery</p>
</li>
<li><p>relay the Redis Pub/Sub event to the browser via the socketio server</p>
</li>
</ul>
<p>To emit the <code>trigger-event</code> of type <code>progress</code> after each Celery progress update:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> socketio
...

<span class="hljs-comment"># redis pub/sub manager</span>
redis_manager = socketio.RedisManager(
    <span class="hljs-string">"redis://localhost:6379"</span>,
    write_only=<span class="hljs-literal">True</span>)

<span class="hljs-meta">@app.task(bind=True)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">task</span>(<span class="hljs-params">self</span>):</span>
    n = <span class="hljs-number">10</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(n):
        ...
        redis_manager.emit(
            event=<span class="hljs-string">"trigger-event"</span>,
            data={<span class="hljs-string">"event"</span>: <span class="hljs-string">"progress"</span>})
        ...
</code></pre>
<p>To relay the event from Redis Pub/Sub to socketio, we use socket.io's server <code>client_manager</code>. The <code>client_manager</code> plays a crucial role in synchronising client information across different server instances. It helps keeping track of connected clients, handling disconnects, and ensuring that events are properly propagated among different servers:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> socketio

<span class="hljs-comment"># redis pub/sub manager</span>
redis_manager = socketio.AsyncRedisManager(
    <span class="hljs-string">"redis://localhost:6379"</span>)

<span class="hljs-comment"># socketio</span>
socketio_server = socketio.AsyncServer(
    async_mode=<span class="hljs-string">"asgi"</span>,
    client_manager=redis_manager)

<span class="hljs-comment"># fastapi</span>
fastapi_app = FastAPI()

<span class="hljs-comment"># socketio + fastapi app</span>
socketio_app = socketio.ASGIApp(
    socketio_server=socketio_server,
    other_asgi_app=fastapi_app)
</code></pre>
<p>Note that Celery is synchronous Python and uses <code>socketio.RedisManager,</code> whereas ASGI, FastAPI and Socketio are asynchronous Python and use <code>socketio.AsyncRedisManager</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And that gives us a full round trip:</p>
<ul>
<li><p>the Celery task writes its progress to the db</p>
</li>
<li><p>it emits an event via Redis' Pub/Sub</p>
</li>
<li><p>the emitted event is relayed via the socket.io server</p>
</li>
<li><p>the incoming socket.io event triggers an event on the body</p>
</li>
<li><p>htmx reacts to this event and reloads the progress bar</p>
</li>
</ul>
<p>I hope you enjoyed this article as much as I did improving the user experience in our app.</p>
<p>The full source code is available on <a target="_blank" href="https://github.com/bstiel/celery-task-progress-bar">GitHub</a>.</p>
<p>Any questions, please drop me an email: bjoern.stiel@celery.school</p>
]]></content:encoded></item><item><title><![CDATA[Celery Tasks: A Guide to SQLAlchemy Session Handling]]></title><description><![CDATA[Before I wrote this article, I hadn't realised that SQLAlchemy is a highly controversial subject. Heated discussions on Reddit and X. Love it or hate it…]]></description><link>https://celery.school/sqlalchemy-session-celery-tasks</link><guid isPermaLink="true">https://celery.school/sqlalchemy-session-celery-tasks</guid><category><![CDATA[celery]]></category><category><![CDATA[sqlalchemy]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Fri, 29 Dec 2023 19:09:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703874743768/d0176af3-d2ec-494a-96ae-6d8ed29bdd9b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Before I wrote this article, I hadn't realised that SQLAlchemy is a highly controversial subject. Heated discussions on Reddit and X. Love it or hate it. The full drama. The polarising nature of the internet aside, what is true about SQLAlchemy is, that</p>
<ul>
<li><p>it has a steeper learning curve than the Django ORM</p>
</li>
<li><p>requires some boilerplate code</p>
</li>
<li><p>you need to know about some lower level concepts</p>
</li>
<li><p>has some difficult-to-digest documentation</p>
</li>
</ul>
<p>If you do use SQLAlchemy, you have to write some boilerplate for your Celery tasks which comes with the risk spaghetti code.</p>
<p>In this article, I will run you through some basic SQLAlchemy concepts and show you how I use SQLAlchemy inside my Celery tasks, without resorting to third party packages, which</p>
<ul>
<li><p>helps you understand how things work</p>
</li>
<li><p>provides a generic solution that works with Flask, FastAPI or anything else, even without a web framework</p>
</li>
</ul>
<h2 id="heading-sqlalchemy-sessions">SQLAlchemy Sessions</h2>
<p>Life in the Django ORM world is pretty simple. Database operations are provided via the model object:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

app = Celery(...)

<span class="hljs-meta">@app.task()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_task</span>():</span>
   book = Book.objects.get(title=<span class="hljs-string">"To Kill a Mockingbird"</span>)
   ...
   book.save()
</code></pre>
<p>In the SQLAlchemy world, things are very different. All database operations are performed through a session object. The session is strictly separate from the model object:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery
<span class="hljs-keyword">from</span> sqlalchemy <span class="hljs-keyword">import</span> create_engine
<span class="hljs-keyword">from</span> sqlalchemy.orm <span class="hljs-keyword">import</span> Session

app = Celery(...)
engine = create_engine(<span class="hljs-string">"..."</span>)

<span class="hljs-meta">@app.task()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_task</span>():</span>
   session = Session(engine)
   book = session.query(Book).filter_by(title=<span class="hljs-string">"To Kill a Mockingbird"</span>).one()
   ...
   session.add(book)
   session.commit()
   session.close()
</code></pre>
<p>The session establishes the conversation with the database and represents a staging area for all objects you've loaded, created or manipulated during its lifespan.</p>
<h2 id="heading-session-management">Session Management</h2>
<p>You can think of SQLAlchemy sessions as database transactions. As a general rule, the lifecycle of a session should be separate and external from functions and objects that access and manipulate database data. Sessions are meant to be short. For example, in the context of an incoming Celery task request, a session should be created at the beginning of the task code and closed at the end, instead of being held open indefinitely and shared across tasks.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery
<span class="hljs-keyword">from</span> sqlalchemy <span class="hljs-keyword">import</span> create_engine
<span class="hljs-keyword">from</span> sqlalchemy.orm <span class="hljs-keyword">import</span> Session

app = Celery(...)
engine = create_engine(<span class="hljs-string">"..."</span>)

<span class="hljs-meta">@app.task()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_task</span>():</span>
   session = Session(engine)
   book = session.query(Book).filter_by(title=<span class="hljs-string">"To Kill a Mockingbird"</span>).one()
   ...
   session.add(book)
   session.commit()
   session.close()
</code></pre>
<p>Or, using a context manager:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery
<span class="hljs-keyword">from</span> sqlalchemy <span class="hljs-keyword">import</span> create_engine
<span class="hljs-keyword">from</span> sqlalchemy.orm <span class="hljs-keyword">import</span> Session

app = Celery(...)
engine = create_engine(<span class="hljs-string">"..."</span>)

<span class="hljs-meta">@app.task()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_task</span>():</span>
   <span class="hljs-keyword">with</span> Session(engine) <span class="hljs-keyword">as</span> session:
      book = session.query(Book).filter_by(title=<span class="hljs-string">"To Kill a Mockingbird"</span>).one()
      ...
      session.add(book)
      session.commit()
</code></pre>
<h2 id="heading-celery-task-class">Celery Task Class</h2>
<p>My issue with the two options above is that it involves a lot of repetitive boiler code inside each task. It would be nice if every Celery task request would come with a ready-to-go session object, without having to create it at the beginning and to close it at the end. Something like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_task</span>(<span class="hljs-params">session</span>):</span>
   book = session.query(Book).filter_by(title=<span class="hljs-string">"To Kill a Mockingbird"</span>).one()
   ...
   session.add(book)
   session.commit()
</code></pre>
<p>As it turns out, injecting the session variable at runtime is not possible. It is possible though to bind the task. A bound task has always the task instance as its first argument.</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.task(bind=True)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_task</span>(<span class="hljs-params">self</span>):</span>
   ...
</code></pre>
<p>By default, <code>self</code> is of type <code>celery.Task</code>. <code>celery.Task</code> defines all methods available for Celery tasks, for example <code>apply_async</code> and <code>retry</code>.</p>
<p>Every interaction between your code and your Celery task as well as every interaction between your worker and your Celery task happens via the <code>celery.Task</code> methods. In fact, when your worker processes a task, it always follows this sequence:</p>
<ol>
<li><p>Run <code>before_start</code></p>
</li>
<li><p>Run the task</p>
</li>
<li><p>Run <code>after_return</code></p>
</li>
</ol>
<p>Even when the task in step 2 throws an exception, <code>after_return</code> is guaranteed to run. You can use this to streamline the SQLAlchemy session creation and teardown:</p>
<ul>
<li><p>create the session in <code>before_start</code></p>
</li>
<li><p>make the session available to the bound task</p>
</li>
<li><p>close the session in <code>after_return</code></p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> celery
<span class="hljs-keyword">from</span> sqlalchemy.orm <span class="hljs-keyword">import</span> Session

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTask</span>(<span class="hljs-params">celery.Task</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.sessions = {}

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">before_start</span>(<span class="hljs-params">self, task_id, args, kwargs</span>):</span>
        self.sessions[task_id] = Session(...)
        super().before_start(task_id, args, kwargs)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">after_return</span>(<span class="hljs-params">self, status, retval, task_id, args, kwargs, einfo</span>):</span>
        session = self.sessions.pop(task_id)
        session.close()
        super().after_return(status, retval, task_id, args, kwargs, einfo)

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">session</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.sessions[self.request.id]
</code></pre>
<p>Note that there is only a single task instance per process, meaning that every task within a process shares the same task object. To isolate SQLAlchemy sessions per task request, I use a dictionary and the unique task request id as key.</p>
<h2 id="heading-putting-it-together">Putting It Together</h2>
<p>So far we have:</p>
<ul>
<li><code>MyTask</code>, a custom <code>celery.Task</code> implementation</li>
</ul>
<ul>
<li>a task, which binds <code>celery.Task</code> to the Celery task</li>
</ul>
<p>What is missing is binding <code>MyTask</code> instead of <code>celery.Task</code> to the task. To do this, Celery provides the <code>base</code> argument:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery
<span class="hljs-keyword">from</span> sqlalchemy <span class="hljs-keyword">import</span> create_engine
<span class="hljs-keyword">from</span> sqlalchemy.orm <span class="hljs-keyword">import</span> Session

app = Celery(...)
engine = create_engine(<span class="hljs-string">"..."</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTask</span>(<span class="hljs-params">celery.Task</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.sessions = {}

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">before_start</span>(<span class="hljs-params">self, task_id, args, kwargs</span>):</span>
        self.sessions[task_id] = Session(...)
        super().before_start(task_id, args, kwargs)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">after_return</span>(<span class="hljs-params">self, status, retval, task_id, args, kwargs, einfo</span>):</span>
        session = self.sessions.pop(task_id)
        session.close()
        super().after_return(status, retval, task_id, args, kwargs, einfo)

<span class="hljs-meta">    @property</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">session</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.sessions[self.request.id] 

<span class="hljs-meta">@app.task(bind=True, base=MyTask)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_task</span>(<span class="hljs-params">self</span>):</span>
    book = self.session.query(Book).filter_by(title=<span class="hljs-string">"To Kill a Mockingbird"</span>).one()
    ...
    self.session.add(book)
    self.session.commit()
</code></pre>
<p>This is a generic solution that delegates SQLAlchemy session handling to a custom Task class. It keeps your task code free from repetitive boilerplate. What do you think? Let me know in the comments 👇.</p>
]]></content:encoded></item><item><title><![CDATA[Celery on Windows: What's the latest?]]></title><description><![CDATA[Celery does no longer officially support Windows. However, it is only the prefork pool that does not work on Windows. This articles explores alternatives.]]></description><link>https://celery.school/celery-on-windows</link><guid isPermaLink="true">https://celery.school/celery-on-windows</guid><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><category><![CDATA[Windows]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Wed, 20 Dec 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/T01GZhBSyMQ/upload/799f86778caee75d3797965be5b68c2b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Celery dropped support for Windows a long time ago, somewhere around version 4. Celery 3 was the last version to support Windows, and back in 2018, when I published the first version of this article, it was a somewhat acceptable workaround.</p>
<p>Not these days. So if you still have the odd Celery task that needs to run on Windows, what are your options in 2024? Time for a reality check. Well, sort of, the reality is that Windows is unsupported and things might work or might not. Or they might work now and stop working later.</p>
<blockquote>
<p>Before you do anything, make sure to pip-install pywin32</p>
</blockquote>
<h2 id="heading-the-prefork-problem"><strong>The prefork Problem</strong></h2>
<p>Celery never really stopped working on Windows. What stopped working was the <a target="_blank" href="https://celery.school/celery-worker-pools#heading-prefork">prefork pool</a>, which is Celery's default pool. The prefork pool is similar to a Python multiprocessing pool but based on the billiard package to cater better for Celery-specific needs.</p>
<p>To cut a long story short: the prefork pool is based on the idea of process forking (hence the name prefork pool and not multiprocessing pool). Windows does not support forking but spawning.</p>
<p>For many years, billiard had a switch deep down in its engine room that would make it either fork or spawn, depending on the operating system. That got removed, and that sealed the end of the prefork pool on Windows.</p>
<p>For some time, there was a hacky way around this, by setting the environment variable <code>FORKED_BY_MULTIPROCESSING</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

os.environ.setdefault(<span class="hljs-string">"FORKED_BY_MULTIPROCESSING"</span>, <span class="hljs-string">"1"</span>)

app = Celery(__name__, broker=<span class="hljs-string">"redis://localhost:6379/0"</span>)
</code></pre>
<p>This no longer works and you do not get what you ask for. Celery creates a new SpawnPoolWorker for each incoming task, you can see incoming tasks being received but it fails to process them.</p>
<h2 id="heading-option-1-going-solo"><strong>Option 1: Going solo</strong></h2>
<p>If the prefork pool is out of bounds, you can still choose another pool type. The solo pool is a simple, single-threaded execution pool. It is so simple, it's not even an execution pool. It simply executes incoming tasks in the same process and thread as the worker.</p>
<pre><code class="lang-bash">C:\Dev&gt;celery --app=app.app worker --pool=solo
</code></pre>
<p>This still works on Windows and is my recommendation for a CPU-heavy workload. If you need more concurrency, you can create multiple solo workers.</p>
<h2 id="heading-option-2-threads"><strong>Option 2: Threads</strong></h2>
<p>The threads in the <a target="_blank" href="https://celery.school/celery-worker-pools#heading-threads">threads pool</a> type are managed directly by the operating system kernel. As long as Python's ThreadPoolExecutor supports Windows threads, this pool type will work on Windows (I probably shouldn't say that). The threads pool is my recommendation for I/O-bound tasks.</p>
<pre><code class="lang-bash">C:\Dev&gt;celery --app=app.app worker --pool=threads --concurrency=8
</code></pre>
<h2 id="heading-option-3-gevent"><strong>Option 3: gevent</strong></h2>
<p>The <a target="_blank" href="https://celery.school/celery-worker-pools#heading-eventlet-and-gevent">gevent pool</a> implements concurrency via greenlets. Greenlets are similar to coroutines in the asyncio world. While one task waits for its result, it yields to another task to do its thing.</p>
<p>Because the gevent package officially supports Windows, the gevent pool remains a suitable option for IO-bound task processing on Windows as long as you are aware of some gevent-specific <a target="_blank" href="https://celery.school/celery-gevent-5-lessons-learned"><strong>complexities</strong></a><strong>.</strong></p>
<pre><code class="lang-bash">C:\Dev&gt;celery --app=app.app worker --pool=gevent --concurrency=8
</code></pre>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, I've looked at three Celery pool options that still work on Windows in 2024:</p>
<ul>
<li><p>solo</p>
</li>
<li><p>threads</p>
</li>
<li><p>gevent</p>
</li>
</ul>
<p>Bear in mind that none of this is officially supported and that whatever works now might not be working in the future.</p>
<p><em>Last updated Dec 20, 2023<br />First published Aug 21, 2018</em></p>
]]></content:encoded></item><item><title><![CDATA[A Quick Guide to Celery Task Routing]]></title><description><![CDATA[By default, Celery routes all tasks to a single queue and all workers consume from this default queue. You can change this behaviour by telling Celery…]]></description><link>https://celery.school/celery-task-routing</link><guid isPermaLink="true">https://celery.school/celery-task-routing</guid><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Tue, 19 Dec 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/kkAie39phZc/upload/00f5d76e9d812e520840f0fed2e22367.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>By default, Celery routes all tasks to a single queue and all workers consume from this default queue. You can change this behaviour by telling Celery which tasks to send to which queues. This is known as task routing.</p>
<p>This is useful if you have slow and fast tasks, and you don't want the slow tasks to interfere with the fast tasks. Or you have a <a target="_blank" href="https://celery.school/celery-gevent-5-lessons-learned">gevent pool</a> worker for IO-bound tasks and a prefork pool worker for <a target="_blank" href="https://celery.school/celery-worker-pools">CPU-heavy tasks</a>.</p>
<h2 id="heading-step-1-configure-taskroutes"><strong>Step 1: Configure task_routes</strong></h2>
<p>The first thing is to assign a queue to each task. For example to route <code>task_1</code> to <code>queue_a</code> and <code>task_2</code> to <code>queue_b</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

app = Celery(
    __name__,
    broker=<span class="hljs-string">"redis://localhost:6379/0"</span>,
    task_routes={
        <span class="hljs-string">"task_1"</span>: {<span class="hljs-string">"queue"</span>: <span class="hljs-string">"queue_a"</span>}
        <span class="hljs-string">"task_2"</span>: {<span class="hljs-string">"queue"</span>: <span class="hljs-string">"queue_b"</span>}
    })
</code></pre>
<h2 id="heading-step-2-worker-queues"><strong>Step 2: Worker queues</strong></h2>
<p>The <code>--queues</code> command line argument makes the Celery worker process tasks from one or multiple queues and ignore everything else. For the example above, I have one worker for <code>queue_a</code>...</p>
<pre><code class="lang-bash"><span class="hljs-comment"># process tasks in queue_a only</span>
$ celery --app=worker.app worker --queues=queue_a
</code></pre>
<p>...and another worker processing tasks from <code>queue_b</code>:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># process tasks in queue_b only</span>
$ celery --app=worker.app worker --queues=queue_b
</code></pre>
<h2 id="heading-bonus-multiple-queues"><strong>Bonus: Multiple queues</strong></h2>
<p>If you want your worker to process tasks from more than one queue, pass a comma-separated list to the <code>--queues</code>argument:</p>
<pre><code class="lang-bash">$ celery --app=worker.app worker --queues=queue_a,queue_b
</code></pre>
<h2 id="heading-step-3-give-it-a-go"><strong>Step 3: Give it a go</strong></h2>
<p>You can find the complete example code on <a target="_blank" href="https://github.com/bstiel/celery-task-routing">GitHub</a>. Clone the repository, create a virtual environment and install the dependencies:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/bstiel/celery-task-routing.git
$ <span class="hljs-built_in">cd</span> celery-task-routing
$ python -m venv venv
$ <span class="hljs-built_in">source</span> venv/bin/activate
$ pip install -r requirements.txt
</code></pre>
<p>Start the Redis message broker:</p>
<pre><code class="lang-bash">$ docker compose up -d
</code></pre>
<p>Start the two Celery workers and the producer, to produce <code>task_1</code> and <code>task_2</code> once a second, inside a look. All three commands are wrapped in a Procfile that you can start via honcho (or foreman):</p>
<pre><code class="lang-bash">$ honcho start
</code></pre>
<p>You will see <code>worker_1</code> processing <code>task_1</code> only, and <code>worker_2</code> processing <code>task_2</code> only.</p>
<pre><code class="lang-bash">11:42:16 worker_1.1  [2023-12-20 11:42:16,904: WARNING/MainProcess] hello from task_1
11:42:16 worker_2.1  [2023-12-20 11:42:16,913: WARNING/MainProcess] hello from task_2
</code></pre>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>In this blog post, you learned how to configure Celery to route tasks to dedicated queues and make Celery workers process tasks from certain queues only.</p>
<p>To achieve that, you need to map tasks to queues. This approach works as long as you only have a limited number of tasks. For more complex setups involving many tasks, queues and even services, <a target="_blank" href="https://celery.school/dynamic-celery-task-routing">dynamic task routing</a> offers a more scalable and maintainable solution.</p>
<p><em>Last updated Dec 19, 2023<br />First published May 29, 2018</em></p>
]]></content:encoded></item><item><title><![CDATA[Filesystem As Broker: A Quick Guide]]></title><description><![CDATA[The filesystem as a Celery message broker is a lightweight alternative to Redis and RabbitMQ. This articles explains how to do it.]]></description><link>https://celery.school/filesystem-celery-message-broker</link><guid isPermaLink="true">https://celery.school/filesystem-celery-message-broker</guid><category><![CDATA[celery]]></category><category><![CDATA[message broker]]></category><category><![CDATA[file system]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Mon, 18 Dec 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cd8iI6VCZow/upload/876dd44117a1ea14b8b5b4b2cf037e1d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Using Redis or RabbitMQ as a Celery message broker can feel a bit over the top when you are just developing locally. In this blog post, I show you a simple alternative: the filesystem as a message broker.</p>
<h2 id="heading-kombu"><strong>Kombu</strong></h2>
<p>Kombu is a messaging library that provides a high-level interface for the AMQ protocol (with RabbitMQ being one of the best-known implementations). Celery uses Kombu to send and receive messages, so any support for a particular broker comes down to Kombu and not Celery.</p>
<p>The message broker is the store which interacts as the transport between the producer and consumer of messages. Redis, RabbitMQ and <a target="_blank" href="https://celery.school/amazon-sqs-celery-broker">Amazon SQS</a> are among the most widely used message brokers.</p>
<p>Kombu also comes with support for File-system transport. The producer and consumer communicate via files. When the producer creates a new message, it writes the message content to a file in a particular directory. The consumer listens for new files in this directory and processes them as they are created.</p>
<h2 id="heading-celery-configuration"><strong>Celery configuration</strong></h2>
<p>Documentation on the file-system transport is a bit sparse, but the setup is straightforward. Use <code>filesystem://</code> as the <code>broker</code>. The actual directory that is used for exchanging messages goes into the <code>broker_transport_options</code> argument:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

app = Celery(
    __name__,
    broker_url=<span class="hljs-string">'filesystem://'</span>,
    broker_transport_options={
        <span class="hljs-string">'data_folder_in'</span>: <span class="hljs-string">'./.data/broker'</span>,
        <span class="hljs-string">'data_folder_out'</span>: <span class="hljs-string">'./.data/broker/'</span>,
    })
</code></pre>
<p>Note that:</p>
<ul>
<li><p><code>data_folder_in</code> and <code>data_folder_out</code> point to the same path</p>
</li>
<li><p>Celery will not create any directories, it is your responsibility to ensure that <code>/.data/broker</code> exists</p>
</li>
</ul>
<h2 id="heading-a-simple-example"><strong>A simple example</strong></h2>
<p>Clone the example <a target="_blank" href="https://github.com/bstiel/celery-filesystem-broker">GitHub repository</a> and follow the installation instructions:</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> https://github.com/bstiel/celery-filesystem-broker.git
$ python -m venv venv
$ venv/bin/activate
$ pip install -r requirements.txt
</code></pre>
<p>Start the Celery worker:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker</span>
$ celery --app=worker.app worker --loglevel=INFO
</code></pre>
<p>Start the producer:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start producer</span>
$ python producer.py
</code></pre>
<p>The producer creates a <code>long_running_task</code> task every two seconds. This gets transported to the <code>./.data/broker</code> directory from which the worker picks it up for processing. The Celery logs should show something like this:</p>
<pre><code class="lang-bash">[2023-12-19 16:44:52,105: INFO/ForkPoolWorker-1] Task long_running_task[a31af3f0-78b8-499f-ae1b-a277c2319bbf] succeeded <span class="hljs-keyword">in</span> 0.15355589999671793s: 501.67632
</code></pre>
<p>Hope you find this useful. Any questions? Please comment below 👇 or drop me an email bjoern.stiel@celery.school.</p>
<p><em>Last updated Dec 19, 2023<br />First published Jul 3, 2018</em></p>
]]></content:encoded></item><item><title><![CDATA[Gevent vs Prefork: Busting the Performance Myth]]></title><description><![CDATA[Do you know what an FKT is? It stands for Fastest Known Time across a specific route or trail. FKTs are popular among trail runners and ultra-distance…]]></description><link>https://celery.school/gevent-vs-prefork-performance</link><guid isPermaLink="true">https://celery.school/gevent-vs-prefork-performance</guid><category><![CDATA[prefork]]></category><category><![CDATA[Python]]></category><category><![CDATA[celery]]></category><category><![CDATA[gevent]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Thu, 14 Dec 2023 14:31:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1702565948423/e1e92561-14b8-44a8-933c-577913959e44.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Do you know what an FKT is? It stands for Fastest Known Time across a specific route or trail. FKTs are popular among trail runners and ultra-distance cyclists.</p>
<p>FKTs are not timed to a specific protocol and there is no claim on an official record. In real life, there are different opinions on what is allowed and different claims on an official record. For example, The Great Divide Trail has a cycling FKT of 12 days, 12 hours and 21 minutes. Or 13 days, 22 hours, and 51 minutes, depending on how much support you think is acceptable.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702553357975/8437f98d-801c-40f3-8552-cdb11065a296.png" alt class="image--center mx-auto" /></p>
<p>Why am I telling you this? Turns out there are some similarities between FKT claims among cyclists and performance claims on Celery worker pools among developers. One of them is: The gevent pool is faster than the prefork pool!</p>
<p>Is this true? Let's find out in this article, in which I am running a little performance experiment between prefork and gevent.</p>
<h2 id="heading-the-prefork-pool">The Prefork Pool</h2>
<p>Celery's <a target="_blank" href="https://celery.school/celery-worker-pools">prefork pool</a> implements concurrency via multiprocessing. If you run with a concurrency of four, Celery creates four memory clones of your app process. If you run with a concurrency of ten, you end up with ten clones, and so forth.</p>
<h2 id="heading-the-gevent-pool">The Gevent Pool</h2>
<p>The <a target="_blank" href="https://celery.school/celery-gevent-5-lessons-learned">Gevent Pool</a> implements concurrency via greenlets. Greenlets are similar to coroutines in the asyncio world: while one task waits for its result, it yields to another task to do its thing. In the Celery case with a gevent pool, there is only one process.</p>
<h2 id="heading-welcome-to-the-lab">Welcome to the Lab</h2>
<p>To establish the Fastest Known Time for draining 1,000 IO-bound tasks, I use the poor man's version of an IO-bound task. The <code>sleep</code> task blocks for 500ms and then exits successfully.</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.task(name="sleep")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sleep</span>():</span>
    time.sleep(<span class="hljs-number">0.5</span>)
</code></pre>
<p>The idea is to create 1,000 <code>sleep</code> tasks and measure how long the Celery worker takes to finish processing all 1,000 <code>sleep</code> tasks. I repeat this experiment multiple times. Each experiment involves a different pool and concurrency setting:</p>
<ul>
<li><p>prefork with a concurrency of 5, 10, 20, 50, 100, 250 and 500</p>
</li>
<li><p>gevent with a concurrency of 5, 10, 20, 50, 100, 250 and 500</p>
</li>
</ul>
<p>The rest of my lab setup is pretty straightforward:</p>
<ul>
<li>I use a dockerised Redis instance as a message broker</li>
</ul>
<ul>
<li><p>I start the Celery worker with the <code>--events</code> flag, so I can capture the task start/finish timestamps</p>
</li>
<li><p>I run a Python script that creates 1,000 <code>sleep</code> tasks as quickly as possible, using the <code>ThreadPoolExecutor</code> pool</p>
</li>
<li><p>Another Python script that captures the Celery events for each experiment and records the first and the last task event timestamp for each experiment.</p>
</li>
<li><p>This gives me the total elapsed time to process all 1,000 tasks for each pool/concurrency setting</p>
</li>
</ul>
<blockquote>
<p>Please bear in mind that all numbers and conclusions in this article refer to IO-bound workload only.</p>
</blockquote>
<h2 id="heading-results">Results</h2>
<p>This is how the Celery worker performs for different concurrency and pool settings, draining all 1,000 tasks:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concurrency</td><td>gevent</td><td>prefork</td></tr>
</thead>
<tbody>
<tr>
<td>5</td><td>103.14s</td><td>100.62s</td></tr>
<tr>
<td>10</td><td>51.35s</td><td>50.41s</td></tr>
<tr>
<td>20</td><td>25.82s</td><td>25.24s</td></tr>
<tr>
<td>50</td><td>10.76s</td><td>10.20s</td></tr>
<tr>
<td>100</td><td>6.36s</td><td>5.31s</td></tr>
<tr>
<td>250</td><td>3.72s</td><td>4.11s</td></tr>
<tr>
<td>500</td><td>3.79s</td><td>5.77s</td></tr>
</tbody>
</table>
</div><p>Or, if you are a visual person:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702561625162/6028788c-3e35-4c33-a604-99131ddd9c16.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-what-does-this-mean">What does this mean?</h2>
<p>If I have 1,000 tasks and each task takes 0.5s to process, how long does it take to process all tasks with a concurrency of one? 1,000 x 0.5s = 500s. And with a concurrency of five 1,000 x 0.5s / 5 = 100s. The theoretical total processing time is simply:</p>
<p><em>Number of Tasks</em> x <em>Processing Time per Task</em> / <em>Concurrency</em></p>
<p>This is what the lab numbers show. Irrespective of the pool in use: gevent is not faster than prefork. In the same sense asynchronous Python is not faster than synchronous Python. Does this mean that you can go with the prefork pool and scale up to a concurrency of 1,000?</p>
<p>Definitely not. The problem with prefork is not that it is slower or blocking. The problem with prefork is that it does not scale efficiently. Remember that, concurrency in a prefork pool means that Celery clones your app process 1,000 times in memory. This means a 1,000x memory footprint. This is why a reasonable concurrency setting for a prefork pool is usually single-digit (ignoring CPU considerations).</p>
<p>Gevent on the other hand is single-threaded and runs inside the worker process. The gevent pool yields control to another task when one task is blocked, for example waiting for a response or sleeping. Concurrency in a gevent context means the number of concurrent tasks your app is configured to process. There are only a few valid reasons to keep the concurrency setting in a gevent pool low. A concurrency setting of &gt;500 can make perfect sense.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>For IO-bound workload, gevent is not faster than prefork. However, for IO-bound workload, gevent is more efficient and scalable than prefork because it does not lead to a bigger memory footprint.</p>
<p>And with that, I am off now, training for an FKT attempt on my Gravel bike.</p>
<p>Are you still confused about when to use prefork and gevent? Shoot me an email at bjoern.stiel@celery.school or leave a comment below 👇.</p>
]]></content:encoded></item><item><title><![CDATA[Boost Your Productivity: Debug Celery Apps With VS Code]]></title><description><![CDATA[By following this Visual Studio Code tutorial, you'll be able to run and debug your Celery + Django + Redis app with a single mouse click.]]></description><link>https://celery.school/celery-debugging-with-vscode</link><guid isPermaLink="true">https://celery.school/celery-debugging-with-vscode</guid><category><![CDATA[Python]]></category><category><![CDATA[celery]]></category><category><![CDATA[vscode]]></category><category><![CDATA[debugging]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Tue, 05 Dec 2023 23:11:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701959146376/7928a1b2-46fe-4433-963a-70d8890347a3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The greatest pain in my local Celery development setup is the overhead of running and debugging multiple things and processes. Most of my Celery apps require at least three components:</p>
<ul>
<li><p>Web application (eg Django, FastAPI or Flask)</p>
</li>
<li><p>Celery worker(s)</p>
</li>
<li><p>Message broker</p>
</li>
</ul>
<p>I have tweaked my local development setup many times, to be able to develop and debug without things getting in my way. After years of using Docker, I have now moved towards Visual Studio Code. My new setup is more productive than anything I have worked with before.</p>
<h2 id="heading-tldr">tl;dr</h2>
<p>Check out my example code on <a target="_blank" href="https://github.com/bstiel/celery-vscode">GitHub</a> and watch my YouTube Video.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=t1V4GB1_HEs">https://www.youtube.com/watch?v=t1V4GB1_HEs</a></div>
<p> </p>
<h2 id="heading-visual-studio-code">Visual Studio Code</h2>
<p>Visual Studio Code (VS Code) is a free, open-source code editor developed by Microsoft. VS Code is lightweight and powerful at the same time, extendible, supports a wide range of programming languages and works cross-platform.</p>
<p>Right out of the gate, VS Code comes with a Python debugger and full support for breakpoints, step-through code and variable inspection 🙌.</p>
<h2 id="heading-launchjson">launch.json</h2>
<p>All of this is fully customisable via a project-specific JSON configuration file, <code>launch.json,</code> which is located inside the <code>.vscode</code> folder, starting at the root of your project.</p>
<p>What does <code>launch.json</code> do for you? With <code>launch.json</code> you can define one or multiple processes that are available to run, alone or together, via VS Code's Run command. With or without debugging.</p>
<p>In the Celery case, this allows you to define the web app, the Celery worker and the message broker in one <code>launch.json</code> configuration. With a single "Run" command you can launch your stack, set breakpoints, debug and inspect variables. To make this work, you need three ingredients:</p>
<ul>
<li><p>configurations</p>
</li>
<li><p>compounds</p>
</li>
<li><p>tasks</p>
</li>
</ul>
<h2 id="heading-configurations">Configurations</h2>
<p>A launch configuration defines the environment setup for running and debugging a single process and includes the command, arguments and environment variables.</p>
<p>For example, the Celery worker process is defined in one launch configuration, and the Django app process in another one. Each launch configuration goes into the <code>configurations</code> property, which can hold as many configurations (processes) as you need.</p>
<p>Here is an example of the Celery and Django launch configurations. To run them individually, select "Run" -&gt; "Start Debugging" (or "Run Without Debugging") from the VS Code menu. Or click the "Run and Debug" icon in the sidebar. You can then select Celery or Django from the dropdown.</p>
<pre><code class="lang-json"><span class="hljs-comment">// launch.json</span>
{
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.2.0"</span>,
    <span class="hljs-attr">"configurations"</span>: [
      {
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Celery"</span>,
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"python"</span>,
            <span class="hljs-attr">"request"</span>: <span class="hljs-string">"launch"</span>,
            <span class="hljs-attr">"module"</span>: <span class="hljs-string">"celery"</span>,
            <span class="hljs-attr">"console"</span>: <span class="hljs-string">"integratedTerminal"</span>,
            <span class="hljs-attr">"args"</span>: [
                <span class="hljs-string">"--app"</span>,
                <span class="hljs-string">"api.worker.app"</span>,
                <span class="hljs-string">"worker"</span>,
                <span class="hljs-string">"--loglevel"</span>,
                <span class="hljs-string">"DEBUG"</span>,
                <span class="hljs-string">"--pool"</span>,
                <span class="hljs-string">"solo"</span>,
            ]
        },
        {
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Django"</span>,
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"python"</span>,
            <span class="hljs-attr">"request"</span>: <span class="hljs-string">"launch"</span>,
            <span class="hljs-attr">"stopOnEntry"</span>: <span class="hljs-literal">false</span>,
            <span class="hljs-attr">"python"</span>: <span class="hljs-string">"${workspaceRoot}/venv/bin/python"</span>,
            <span class="hljs-attr">"program"</span>: <span class="hljs-string">"${workspaceRoot}/manage.py"</span>,
              <span class="hljs-attr">"args"</span>: [
                  <span class="hljs-string">"runserver"</span>
              ],
        }        
    ],
    <span class="hljs-attr">"compounds"</span>: [
        {
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Celery and Django"</span>,
            <span class="hljs-attr">"configurations"</span>: [<span class="hljs-string">"Celery"</span>, <span class="hljs-string">"Django"</span>]
        }
    ]}
</code></pre>
<h2 id="heading-compounds">Compounds</h2>
<p>You can now run and debug Django and Celery individually. To run both configurations simultaneously, you need compounds. A compound configuration allows you to run multiple launch configurations together.</p>
<p>Once set up, compounds are available via the Run/Debug dropdown menu to choose from, just like configurations.</p>
<pre><code class="lang-json"><span class="hljs-string">"compounds"</span>: [
        {
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Celery and Django"</span>,
            <span class="hljs-attr">"configurations"</span>: [<span class="hljs-string">"Celery"</span>, <span class="hljs-string">"Django"</span>]
        }
]
</code></pre>
<h2 id="heading-message-broker">Message Broker</h2>
<p>You can now run and debug the Django and Celery app processes There is one last thing missing to make this work, and that is the message broker. Here are three options to run, say, Redis as a broker:</p>
<ol>
<li><p>Install Redis on the development computer</p>
</li>
<li><p>Run Redis inside a Docker container</p>
</li>
<li><p>Don't use Redis and use the filesystem instead 😁</p>
</li>
</ol>
<p>I don't like installing dependencies on my computer. Using the <a target="_blank" href="https://celery.school/filesystem-celery-message-broker">filesystem as a broker</a> is a dependency-free alternative. However, I prefer my development stack to mirror my production stack as closely as possible. That leaves me with the dockerised Redis option.</p>
<h2 id="heading-tasksjson">tasks.json</h2>
<p>The VS Code <code>launch.json</code> configurations are mainly for debugging. What I want is to automatically start Redis before running/debugging and to automatically shut it down after everything else.</p>
<p>The launch configuration provides two properties to support that:</p>
<ul>
<li><p><code>preLaunchTask</code>: run the <code>start-redis-container</code> task when starting up</p>
</li>
<li><p><code>postDebugTask</code>: run the <code>stop-redis-container</code> task when shutting down</p>
</li>
</ul>
<pre><code class="lang-json"><span class="hljs-comment">// launch.json</span>
{
       <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Django"</span>,
       <span class="hljs-attr">"type"</span>: <span class="hljs-string">"python"</span>,
       <span class="hljs-attr">"request"</span>: <span class="hljs-string">"launch"</span>,
       <span class="hljs-attr">"stopOnEntry"</span>: <span class="hljs-literal">false</span>,
       <span class="hljs-attr">"python"</span>: <span class="hljs-string">"${workspaceRoot}/venv/bin/python"</span>,
       <span class="hljs-attr">"program"</span>: <span class="hljs-string">"${workspaceRoot}/manage.py"</span>,
          <span class="hljs-attr">"args"</span>: [
             <span class="hljs-string">"runserver"</span>
          ],
       <span class="hljs-attr">"preLaunchTask"</span>: <span class="hljs-string">"start-redis-container"</span>,
       <span class="hljs-attr">"postDebugTask"</span>: <span class="hljs-string">"stop-redis-container"</span>
}
</code></pre>
<p>In case you do wonder why I attach both tasks to the Django and not the Celery container, there is no reason. It simply does not matter in this case.</p>
<p>What are tasks?<code>start-redis-container</code> and <code>stop-redis-container</code>are defined in the<code>tasks.json</code> file, inside the <code>.vscode</code> subfolder. Tasks are commands, in my case <code>start-redis-container</code> and <code>stop-redis-container</code> are defined as <code>docker run</code> and <code>docker rm</code> commands, respectively.</p>
<pre><code class="lang-json"><span class="hljs-comment">// tasks.json</span>
{
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"2.0.0"</span>,
    <span class="hljs-attr">"tasks"</span>: [
        {
            <span class="hljs-attr">"label"</span>: <span class="hljs-string">"start-redis-container"</span>,
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"shell"</span>,
            <span class="hljs-attr">"command"</span>: <span class="hljs-string">"docker"</span>,
            <span class="hljs-attr">"args"</span>: [
              <span class="hljs-string">"run"</span>,
              <span class="hljs-string">"-d"</span>,
              <span class="hljs-string">"--name"</span>,
              <span class="hljs-string">"redis"</span>,
              <span class="hljs-string">"-p"</span>,
              <span class="hljs-string">"6379:6379"</span>,
              <span class="hljs-string">"redis:latest"</span>
            ],
          },
          {
            <span class="hljs-attr">"label"</span>: <span class="hljs-string">"stop-redis-container"</span>,
            <span class="hljs-attr">"type"</span>: <span class="hljs-string">"shell"</span>,
            <span class="hljs-attr">"command"</span>: <span class="hljs-string">"docker"</span>,
            <span class="hljs-attr">"args"</span>: [
              <span class="hljs-string">"rm"</span>,
              <span class="hljs-string">"-f"</span>,
              <span class="hljs-string">"redis"</span>
            ],
          }

    ]
}
</code></pre>
<p>This gives you a fully functioning, debuggable Celery/Django/Redis development stack for VS Code.</p>
<p>Make sure to check out my <a target="_blank" href="https://github.com/bstiel/celery-vscode">example code</a>, including <code>launch.json</code> and <code>tasks.json</code>.</p>
<p>Do you have a question or a comment? I love to hear from you, comment below 👇 or drop me an email: bjoern.stiel@celery.school.</p>
]]></content:encoded></item><item><title><![CDATA[Optimising Celery Performance: A Guide to Load Testing with Locust.io]]></title><description><![CDATA[Optimize Celery load testing using Locust.io to evaluate app capacity, stability, and response times. Analyze metrics, resolve bottlenecks]]></description><link>https://celery.school/celery-load-testing</link><guid isPermaLink="true">https://celery.school/celery-load-testing</guid><category><![CDATA[celery]]></category><category><![CDATA[locust]]></category><category><![CDATA[Load Testing]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Mon, 04 Dec 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700518620735/9f935efb-d2b1-44c0-aeaf-3ac508003bde.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Load testing is a way to determine the capacity, stability and response times of your application.</p>
<p>During a load test, some specialised load testing software simulates demand on your app by spawning concurrent users and collects metrics such as response times and error rates.</p>
<p>These metrics show you a picture of how many concurrent requests your application can handle and help you identify and address bottlenecks.</p>
<h3 id="heading-locust"><strong>Locust</strong></h3>
<p><a target="_blank" href="https://locust.io/?ref=celery-school.ghost.io">Locust</a> is an open-source, Python-based load-testing tool. Locust is scriptable, developer-friendly and includes an easy-to-use web user interface. Locust (version 2.15.1) requires Python 3.7 or newer. Install the locust package with pip and verify your locust installation:</p>
<pre><code class="lang-bash">$ pip install locust
$ locust -V
</code></pre>
<h2 id="heading-first-steps-with-locust"><strong>First steps with Locust</strong></h2>
<p>Similar to Python unit tests, Locust test cases are scripted in plain Python code and go into a special file,<a target="_blank" href="https://locust.io/?ref=celery-school.ghost.io"><code>locustfile.py</code></a>. Let's say we wanted to load-test an app that exposes these two REST endpoints:</p>
<ul>
<li><p><code>GET /</code></p>
</li>
<li><p><code>GET /users</code></p>
</li>
</ul>
<pre><code class="lang-Python"><span class="hljs-comment"># loucstfile.py</span>
<span class="hljs-keyword">from</span> locust <span class="hljs-keyword">import</span> HttpUser, task

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">APIClient</span>(<span class="hljs-params">HttpUser</span>):</span>

<span class="hljs-meta">    @task</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_home</span>(<span class="hljs-params">self</span>):</span>
        self.client.get(<span class="hljs-string">"/"</span>)

<span class="hljs-meta">    @task</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_users</span>(<span class="hljs-params">self</span>):</span>
        self.client.get(<span class="hljs-string">"/users"</span>)
</code></pre>
<p>A Locust test class always inherits from<code>locust.User</code>. In this case, I use the specialised<code>locust.HttpUser</code>, which provides support for HTTP-based load tests. I write one method for each endpoint. Save to <code>locustfile.py</code> and start Locus like so:</p>
<pre><code class="lang-bash">$ locust --host=http://localhost:8000 --users=50 --spawn-rate=10 --autostart
</code></pre>
<p>Locust runs the two test cases <code>APIClient.test_home</code> and <code>APIClient.test_users</code> against <a target="_blank" href="https://locust.io/?ref=celery-school.ghost.io"><code>http://localhost:8000/</code></a> and <a target="_blank" href="https://locust.io/?ref=celery-school.ghost.io"><code>http://localhost:8000/users</code></a> respectively, spawning 10 new users per second (spawn-rate) until it reaches a total number of 50 concurrent users.</p>
<p>The two tests are picked at random, resulting in a 50/50 distribution. This this can be configured by applying different weightings per test method.</p>
<p>Head over to the Locust web UI at <a target="_blank" href="https://locust.io/?ref=celery-school.ghost.io"><code>http://localhost:8089</code></a> which provides several metrics as well as manual control parameters.</p>
<h2 id="heading-locust-and-celery"><strong>Locust and Celery</strong></h2>
<p>You can use Locust to run load tests against <em>anything</em>, including Celery. Unfortunately, Locust does not come with Celery battery included, so some customisation is required. Essentially, we need to code up the Celery equivalent of the <code>locust.HttpUser</code>.</p>
<p>The trick is to wrap the Celery client so we can pass information to Locust about the Celery task's name, start and end time and task exceptions.</p>
<pre><code class="lang-Python"><span class="hljs-comment"># locustfile.py</span>
<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> datetime
<span class="hljs-keyword">import</span> ssl
<span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery
<span class="hljs-keyword">from</span> locust <span class="hljs-keyword">import</span> User, between, task, events

<span class="hljs-meta">@events.init_command_line_parser.add_listener</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_</span>(<span class="hljs-params">parser</span>):</span>
    <span class="hljs-string">"""
    Additional command line/ui argument for Celery backend url.
    """</span>
    parser.add_argument(<span class="hljs-string">"--backend"</span>, type=str, env_var=<span class="hljs-string">"LOCUST_CELERY_BACKEND"</span>, default=<span class="hljs-string">""</span>, required=<span class="hljs-literal">True</span>, include_in_web_ui=<span class="hljs-literal">True</span>, help=<span class="hljs-string">"Celery backend url"</span>)


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CeleryClient</span>:</span>
    <span class="hljs-string">"""
    CeleryClient is a wrapper around the Celery client.
    It proxies any function calls and fires the *request* event when they finish,
    so that the calls get recorded in Locust.
    """</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, broker, backend, task_timeout, broker_pool_limit, request_event</span>):</span>
        kwargs = {
            <span class="hljs-string">"broker"</span>: broker,
            <span class="hljs-string">"backend"</span>: backend,
            <span class="hljs-string">"broker_pool_limit"</span>: broker_pool_limit
        }

        <span class="hljs-comment"># support SSL/TLS redis broker</span>
        <span class="hljs-keyword">if</span> broker.startswith(<span class="hljs-string">"rediss://"</span>):
            kwargs[<span class="hljs-string">"broker_use_ssl"</span>] = {<span class="hljs-string">"ssl_cert_reqs"</span>: ssl.CERT_NONE}

        <span class="hljs-comment"># support SSL/TLS redis backend</span>
        <span class="hljs-keyword">if</span> backend.startswith(<span class="hljs-string">"rediss://"</span>):
            kwargs[<span class="hljs-string">"redis_backend_use_ssl"</span>] = {<span class="hljs-string">"ssl_cert_reqs"</span>: ssl.CERT_NONE}

        self.client = Celery(**kwargs)
        self.task_timeout = task_timeout
        self._request_event = request_event

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_task</span>(<span class="hljs-params">self, name, args=None, kwargs=None, queue=None</span>):</span>
        options = {}
        <span class="hljs-keyword">if</span> queue:
            options[<span class="hljs-string">"queue"</span>] = queue

        request_meta = {
            <span class="hljs-string">"request_type"</span>: <span class="hljs-string">"celery"</span>,
            <span class="hljs-string">"response_length"</span>: <span class="hljs-number">0</span>,
            <span class="hljs-string">"name"</span>: name,
            <span class="hljs-string">"start_time"</span>: time.time(),
            <span class="hljs-string">"response"</span>: <span class="hljs-literal">None</span>,
            <span class="hljs-string">"context"</span>: {},
            <span class="hljs-string">"exception"</span>: <span class="hljs-literal">None</span>,
        }
        t0 = datetime.datetime.utcnow()
        <span class="hljs-keyword">try</span>:
            async_result = self.client.send_task(name, args=args, kwargs=kwargs, **options)
            result = async_result.get(self.task_timeout)  <span class="hljs-comment"># blocking</span>
            request_meta[<span class="hljs-string">"response"</span>] = result
            t1 = async_result.date_done
        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
            t1 = <span class="hljs-literal">None</span>
            request_meta[<span class="hljs-string">"exception"</span>] = e

        request_meta[<span class="hljs-string">"response_time"</span>] = <span class="hljs-literal">None</span> <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> t1 <span class="hljs-keyword">else</span> (t1 - t0).total_seconds() * <span class="hljs-number">1000</span>
        self._request_event.fire(**request_meta)  <span class="hljs-comment"># this is what makes the request actually get logged in Locust</span>
        <span class="hljs-keyword">return</span> request_meta[<span class="hljs-string">"response"</span>]


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CeleryUser</span>(<span class="hljs-params">User</span>):</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, environment</span>):</span>
        super().__init__(environment)
        self.client = CeleryClient(
            broker=environment.host,
            backend=environment.parsed_options.backend,
            task_timeout=environment.stop_timeout,
            request_event=environment.events.request)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CeleryTask</span>(<span class="hljs-params">CeleryUser</span>):</span>
<span class="hljs-meta">    @task</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_task1</span>(<span class="hljs-params">self</span>):</span>
        self.client.send_task(<span class="hljs-string">"task1"</span>)

<span class="hljs-meta">    @task</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_task2</span>(<span class="hljs-params">self</span>):</span>
        self.client.send_task(<span class="hljs-string">"task2"</span>)
</code></pre>
<p>The magic happens around the <code>request_event</code> variable which is exposed via the <code>environment</code>property, which in turn is available on the <code>locust.User</code> class.</p>
<p>The idea is to capture essential information like start time, end time, exception and response and pass them off to Locust via a set of keyword arguments:</p>
<pre><code class="lang-Python">self._request_event.fire(
    request_type=<span class="hljs-string">"celery"</span>,
    response_length=<span class="hljs-number">0</span>,
    name=...,
    start_time=...,
    response_time=...
    response=...,
    context={},
    exception=...)
</code></pre>
<p>Remember that Celery tasks are asynchronous by design. Here, <code>async_result.get(...)</code> explicitly waits for the task to finish so we can capture the response and response time as well as any exception. This blocks the simulated Celery user that Locust spawns.</p>
<p>However, Locust "spawns" exactly one greenlet per simulated user. This means that a greenlet that waits for a Celery task to finish, does not block any other concurrent greenlet.</p>
<h2 id="heading-timeouts">Timeouts</h2>
<p>By default, <code>async_result.get(...)</code> does not time out. You can use the command line option <code>--stop-timeout</code> to set a task timeout in seconds. It depends on your Celery settings and task configuration (eg soft and hard time limits) whether you want to perform the load test with a timeout.</p>
<p>For example, if you want a task to be recorded as failed after 30 seconds, use a 30-second timeout:</p>
<pre><code class="lang-bash">$ locust --host=http://localhost:8000 --users=50 --spawn-rate=10 --stop-timeout=30 --autostart
</code></pre>
<p>The source code to run Locust against Celery is available on <a target="_blank" href="https://github.com/bstiel/grasshopper">Github</a>.</p>
<p>Do you load-test your Celery cluster? I would love to hear from you. Leave a comment below 👇 or drop me an email: bjoern.stiel@celery.school.</p>
]]></content:encoded></item><item><title><![CDATA[The Gevent Pool: 5 Lessons Learned]]></title><description><![CDATA[If you run Celery tasks to perform API requests or other input/output operations and you want to increase throughput, then this is for you. Gevent is a…]]></description><link>https://celery.school/celery-gevent-5-lessons-learned</link><guid isPermaLink="true">https://celery.school/celery-gevent-5-lessons-learned</guid><category><![CDATA[gevent]]></category><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Fri, 24 Nov 2023 16:13:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700843410814/91b4d0bc-86b4-4f80-9d3b-2b74523ebd85.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you run Celery tasks to perform API requests or other input/output operations and you want to increase throughput, then this is for you.</p>
<h2 id="heading-greenlets">Greenlets</h2>
<p>Gevent is a Python library that provides lightweight, cooperative concurrency via greenlets. Greenlets are the same thing as coroutines in the asyncio world: while one task waits for its result, it yields to another task to do its thing.</p>
<p>Both gevent and asyncio use an event loop for coordinating the execution of tasks. The difference between greenlet and asyncio is that greenlets do the switching between tasks magically, whereas asyncio makes you <em>await</em> explicitly.</p>
<p>In the gevent world, whenever your programme is blocked on a network request, it will automatically switch to another greenlet. This increases throughput for all input/output bound tasks, compared to the default prefork pool.</p>
<h2 id="heading-monkey-patcher">Monkey Patcher</h2>
<p>This magic works because gevent monkey-patches Python’s socket library. Gevent replaces attributes of the standard library's modules with its own modules. This allows you to write traditional synchronous code without noticing how gevent takes over under the hood.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://tenor.com/en-GB/view/yoda-patience-you-must-have-patience-gif-15254127">https://tenor.com/en-GB/view/yoda-patience-you-must-have-patience-gif-15254127</a></div>
<p> </p>
<h3 id="heading-getting-started-with-gevent">Getting Started With Gevent</h3>
<p>Coming from prefork and getting started with gevent is more than just plug-and-play. Are you in the business of giving the gevent pool a try? Here are my top 5 lessons learned.</p>
<h3 id="heading-1-monkey-patching"><strong>1. Monkey patching</strong></h3>
<p>The very first thing gevent needs to do in the lifecycle of a programme is to patch parts of the standard library with gevent-friendly functions. Celery takes care of this. Do not monkey-patch. If something goes wrong, Celery not monkey-patching is never the issue. It's a red herring, contrary to what people say on StackOverflow.</p>
<h3 id="heading-2-3rd-party-sdks-and-api-wrappers"><strong>2. 3rd party SDKs and API wrappers</strong></h3>
<p>Third-party libraries are the single biggest cause for gevent related headaches. Some libraries don't play nicely with the patched socket library. The more third-party packages you rely on the more time you will spend on this. Package dependency hell is a thing.</p>
<h3 id="heading-3-exceptions"><strong>3. Exceptions</strong></h3>
<p>When things do go wrong, be mindful of the exceptions you see. They can be misleading and point you towards components that are not at fault. If you come across any of the following messages in your stack trace, chances are high that it is not your ORM but a third-party SDK (see point 2):</p>
<ul>
<li><p>Module 'select' has no attribute 'epoll'</p>
</li>
<li><p>SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async</p>
</li>
<li><p>You cannot use AsyncToSync in the same thread as an async event loop</p>
</li>
</ul>
<h3 id="heading-4-things-might-work-1000-times-and-then-fail">4. Things might work 1,000 times and then fail</h3>
<p>This is the worst one and is difficult to reproduce. A task might run 1,000 times and then fail with a stack trace that doesn't make sense (see point 3). A good starting point is point 2.</p>
<h3 id="heading-5-3rd-party-sdks-and-api-wrappers"><strong>5. 3rd party SDKs and API wrappers</strong></h3>
<p>I just want to reiterate points 2-4. In 9 out of 10 cases, it is a third-party API wrapper.</p>
]]></content:encoded></item><item><title><![CDATA[Celery via Azure Service Bus: a 5-Step Guide]]></title><description><![CDATA[Here's a little secret. I like hanging out on LinkedIn and chatting to strangers about Celery. Sometimes it's a coincidence, sometimes I creepily sneak up…]]></description><link>https://celery.school/celery-azure-service-bus</link><guid isPermaLink="true">https://celery.school/celery-azure-service-bus</guid><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><category><![CDATA[Azure]]></category><category><![CDATA[Azure Service Bus]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Wed, 22 Nov 2023 22:27:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/yGPxCYPS8H4/upload/40dc2bb3707aeb3aada5c3df66576fc8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here's a little secret. I like hanging out on LinkedIn and chatting to strangers about Celery. Sometimes it's a coincidence, sometimes I creepily sneak up on people I have come across on podcasts or blog posts.</p>
<p>A couple of days ago I was chatting to a friendly chap over in Chicago. And he was telling me that he ran some Celery ETL jobs via Azure Service Bus.</p>
<p>This made me curious. I was just finishing an article about <a target="_blank" href="https://celery.school/amazon-sqs-celery-broker">Amazon SQS as a Celery broker</a> and it would be interesting to compare SQS against Azure Service Bus.</p>
<h3 id="heading-service-bus-queues-and-topics">Service Bus Queues and Topics</h3>
<p>Azure Service Bus is a cloud-based, fully managed message broker provided by Azure, the Microsoft cloud computing platform. The Azure Service Bus cloud service uses the AMQP 1.0 protocol as its primary means of communication. Azure provides two messaging patterns:</p>
<ul>
<li><p>Queues offer First In, First Out (FIFO) message delivery to one or more competing consumers. Only one message consumer receives and processes each message.</p>
</li>
<li><p>Topics provide a one-to-many form of communication in a publish and subscribe pattern. Publisher sends a message to a topic and one or more subscribers receive a copy of the message.</p>
</li>
</ul>
<p>In this article, I will be using queues. I did not manage to get topics working even though Celery's messaging library <a target="_blank" href="https://github.com/celery/kombu">kombu</a> suggests otherwise. If you know more, please comment below 👇.</p>
<h3 id="heading-costs">Costs</h3>
<p>Azure Service Bus offers three <a target="_blank" href="https://azure.microsoft.com/en-gb/pricing/details/service-bus">pricing tiers</a>: Basic, Standard and Premium. The Basic plan offers shared capacity and pricing is based on usage at USD 0.05/1 million ops/month. The Premium plan includes dedicated capacity at a fixed price, around USD 668/month.</p>
<h3 id="heading-step-1-create-a-service-bus-namespace">Step 1: Create a Service Bus Namespace</h3>
<p>Head over to the Microsoft Azure Portal, search for Service Bus and create a namespace. A namespace defines the scope for addressing Service Bus resources within your application.</p>
<p>For example, you can use your application name to scope all queues used within your application. Click "Review + create" which takes you to the review page. Click "create" to continue.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700687135274/fb519576-b853-4b66-9d26-7de89eb4dbf7.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-2-create-a-queue">Step 2: Create a Queue</h3>
<p>Create a queue as soon as the namespace is provisioned. The provisioning process can take a minute or so. Select a name for the queue, and leave the settings as they are. Make a note of the namespace which you will need for the Celery config.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700688257244/5767d9c4-5265-464a-84e8-3de1cae60f9b.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-3-credentials">Step 3: Credentials</h3>
<p>Get the credentials, by following the arrows in the screenshot below. Please note that Microsoft does not recommend <a target="_blank" href="https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-sas">Shared access policies</a>. However, it is safe and simple enough for this tutorial. Make sure that all three claims are selected: Manage, Send and Listen. Copy the Policy name and the Primary Key. You will need them for configuring Celery.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700689345982/f2e02d46-66af-4be9-ad20-485eb4997dc2.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-4-install-pip-packages">Step 4: Install pip packages</h3>
<p>You are now done in the Azure Portal. Apart from Celery, and anything else you might need, install these two pip packages:</p>
<ul>
<li><p>azure-servicebus</p>
</li>
<li><p>azure-identity</p>
</li>
</ul>
<pre><code class="lang-bash">$ pip install azure-servicebus azure-identity
</code></pre>
<h3 id="heading-step-5-configure-celery">Step 5: Configure Celery</h3>
<p>The last step is the Celery configuration. In its most basic form, Celery needs the namespace, Shared Access Policy name and the Primary Key.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

sas_policy_name = <span class="hljs-string">"RootManageSharedAccessKey"</span>
sas_key = <span class="hljs-string">"..."</span>
namespace = <span class="hljs-string">"..."</span>

app = Celery(
    <span class="hljs-string">"app"</span>,
    broker_url=<span class="hljs-string">f"azureservicebus://<span class="hljs-subst">{sas_policy_name}</span>:<span class="hljs-subst">{sas_key}</span>@<span class="hljs-subst">{namespace}</span>"</span>
)
</code></pre>
<p>Start the worker, passing the queue argument to make the Worker consume from the celery queue. This should match the Azure Service bus queue name you created in Step 2. Start the Celery worker and you are in business!</p>
<pre><code class="lang-python">$ celery --app=worker.app worker --queue=celery
</code></pre>
<h3 id="heading-additional-config-options">Additional Config Options</h3>
<p>You can fine-tune Celery using the <code>broker_transport_options</code> dictionary.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

sas_policy_name = <span class="hljs-string">"RootManageSharedAccessKey"</span>
sas_key = <span class="hljs-string">"..."</span>
namespace = <span class="hljs-string">"..."</span>

app = Celery(
    <span class="hljs-string">"app"</span>,
    broker_url=<span class="hljs-string">f"azureservicebus://<span class="hljs-subst">{sas_policy_name}</span>:<span class="hljs-subst">{sas_key}</span>@<span class="hljs-subst">{namespace}</span>"</span>
    broker_transport_options={
        <span class="hljs-string">"queue_name_prefix"</span>: <span class="hljs-string">"..."</span>,
        <span class="hljs-string">"wait_time_seconds"</span>: <span class="hljs-number">5</span>,
        <span class="hljs-string">"peek_lock_seconds"</span>: <span class="hljs-number">60</span>,
        <span class="hljs-string">"uamqp_keep_alive_interval"</span>: <span class="hljs-number">30</span>,
        <span class="hljs-string">"retry_total"</span>: <span class="hljs-number">3</span>,
        <span class="hljs-string">"retry_backoff_factor"</span>: <span class="hljs-number">0.8</span>,
        <span class="hljs-string">"retry_backoff_max"</span>: <span class="hljs-number">120</span>
    }
)
</code></pre>
<ul>
<li><p><code>queue_name_prefix</code>: string prefix to prepend to queue names in a service bus namespace; when<code>task_create_missing_queues=True</code> (or omitted), this auto creates queues (in which case you can skip Step 2) and prepends the queue names with the string prefix</p>
</li>
<li><p><code>wait_time_seconds</code>: number of seconds to wait to receive messages, defaults to 5 seconds</p>
</li>
<li><p><code>peek_lock_seconds</code>: number of seconds the message is visible for before it goes back into the queue and gets sent to another consumer; defaults to 60 seconds</p>
</li>
<li><p><code>uamqp_keep_alive_interval</code>: interval in seconds the Azure uAMQP library should send keepalive messages; defaults to 30 seconds</p>
</li>
<li><p><code>retry_total</code>: Azure SDK retry total; 3 retries by default</p>
</li>
<li><p><code>retry_backoff_factor</code>: Azure SDK exponential backoff factor; default is 0.8</p>
</li>
<li><p><code>retry_backoff_max</code>: Azure SDK retry total time; defaults to 120 seconds</p>
</li>
</ul>
<p>I hope this article was useful. Thanks for reading, and special thanks to my Chicago LinkedIn connection for the inspiration.</p>
<p>If you have any questions, please comment below👇.</p>
]]></content:encoded></item><item><title><![CDATA[Mini Tutorial: Use Amazon SQS as a Celery Message Broker]]></title><description><![CDATA[Amazon Simple Queue Service (Amazon SQS) is a fully managed message queuing service provided by Amazon Web Services (AWS). It is designed for reliability…]]></description><link>https://celery.school/amazon-sqs-celery-broker</link><guid isPermaLink="true">https://celery.school/amazon-sqs-celery-broker</guid><category><![CDATA[message broker]]></category><category><![CDATA[celery]]></category><category><![CDATA[SQS]]></category><category><![CDATA[AWS]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Wed, 15 Nov 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700513938658/ad6c75af-a4c3-4b61-8218-73a2b1aefda7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Amazon Simple Queue Service (Amazon SQS) is a fully managed message queuing service provided by Amazon Web Services (AWS).</p>
<p>It is designed for reliability, resilience, fault tolerance and scalability. Any number of messages between any number of systems, at any volume and without loss. Without the overhead of managing dedicated messaging software and infrastructure. In this this article, I will:</p>
<ul>
<li><p>explain what SQS is and how it works</p>
</li>
<li><p>talk about costs</p>
</li>
<li><p>discuss when SQS as a Celery message broker is (not) a good idea</p>
</li>
<li><p>create and configure an SQS queue</p>
</li>
<li><p>configure Celery for SQS</p>
</li>
</ul>
<h2 id="heading-how-does-amazon-sqs-work"><strong>How does Amazon SQS work?</strong></h2>
<p>Communication between producers/consumers and SQS is via HTTP/HTTPS. Consumers (workers in Celery jargon) actively request messages from a queue via HTTP/HTTP. Both short and long polling are supported.</p>
<p>When a consumer receives a message from a queue, the message remains in the queue. To prevent other consumers from processing the same message, SQS makes the message invisible to other consumers for a set length of time. This visibility timeout begins when SQS returns the message to the consumer.</p>
<p>It is the consumer’s responsibility to delete the message from the queue after processing it. SQS only deletes a message from the queue when it reaches the end of a (configurable) retention period (default 4 days).</p>
<p>If the consumer fails to delete the message before the visibility timeout expires, the message becomes visible again and as a result available to other consumers.</p>
<p>SQS offers two types of message queues: Standard and FIFO (first in, first out).</p>
<h2 id="heading-sqs-standard-queue"><strong>SQS Standard Queue</strong></h2>
<p>Standard queues support very high throughput and can handle a nearly unlimited number of transactions per second:</p>
<ul>
<li><p>messages might be delivered in a different order than they were sent</p>
</li>
<li><p>messages are delivered at least once but may be delivered more than once even when completed within the visibility timeout</p>
</li>
<li><p>responsibility for not processing a message more than once lies with the consumer</p>
</li>
</ul>
<h2 id="heading-sqs-fifo-queue"><strong>SQS FIFO Queue</strong></h2>
<p>FIFO queues can handle up to 3000 messages per second:</p>
<ul>
<li><p>messages are delivered exactly once</p>
</li>
<li><p>message ordering is strictly preserved (first in, first out)</p>
</li>
</ul>
<h2 id="heading-costs"><strong>Costs</strong></h2>
<p>The first one million SQS requests per month are free. After that, prices start at $0.40 per million requests, depending on the region. A request is not the same as a message. So what counts as an SQS request?</p>
<ul>
<li><p>every Amazon SQS API action counts as a request</p>
</li>
<li><p>pushing a message to SQS is one request</p>
</li>
<li><p>SQS is polling based, every time a consumer polls a queue, it counts as a request (ka-ching!)</p>
</li>
<li><p>a single request can have up to 10 messages / max total payload of 256 KB</p>
</li>
<li><p>every 64 KB chunk of a message is a request, a 128 KB payload is billed as 2 requests</p>
</li>
<li><p>the worker startup stuff like creating a queue, and listing existing queues are all requests</p>
</li>
</ul>
<p>One million requests translate roughly to one request every two seconds. It is a number with many caveats (see above), but it gives you an idea of which bracket your app falls into. For the whole SQS pricing shebang, <a target="_blank" href="https://aws.amazon.com/sqs/pricing/">check out the Amazon SQS Pricing Details</a>.</p>
<h2 id="heading-sqs-as-a-celery-message-broker"><strong>SQS as a Celery message broker</strong></h2>
<p>SQS shines when it comes to high availability, high-throughput and guaranteed at-least-once delivery. To me, the no-loss guarantee is its most compelling feature. I like its proven polling-based architecture.</p>
<p>SQS is a reliable workhorse, solid but a bit slow. If you are after a fast sports car, SQS is not for you. Note that some worker remote control commands are unavailable with SQS. Because SQS does not support events, you cannot use Celery events, celerymon, flower or the Django Admin monitor.</p>
<h3 id="heading-tutorial-run-celery-with-sqs"><strong>Tutorial: Run Celery with SQS</strong></h3>
<p>I assume you have an AWS account and some familiarity with the <a target="_blank" href="https://console.aws.amazon.com/">AWS Management Console</a>. If you are completely new to AWS, make sure to create an AWS account first.</p>
<p>You can create SQS queues without the AWS management console using the AWS CLI or directly via Celery. Drop me an email at <a target="_blank" href="https://aws.amazon.com/sqs/pricing/">bjoern.stiel@celery.school</a>, and I will give you some pointers.</p>
<h3 id="heading-step-1-create-an-sqs-queue"><strong>Step 1: Create an SQS Queue</strong></h3>
<p>Log into the AWS Management Console, and use the search bar at the top to find “SQS”. It will suggest a list of services as you type. Click on “Simple Queue Service”. Next, hit “Create queue”. This takes you to the view which allows you to create a queue.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700652558748/061aeb55-7aff-478e-b816-cc22cd4b6f5d.png" alt class="image--center mx-auto" /></p>
<p>Select the queue type. If you are unsure, use Standard. I will touch upon a few FIFO aspects in this tutorial, however, they come with some nitty-gritty details which merit a separate article.</p>
<p>Choose a name for a queue and note that queue type and name cannot be changed once you have created the queue.</p>
<p>Next up are the queue settings (which can be changed later). Note that I am switching from SQS to Celery terminology now:</p>
<ul>
<li><p><strong>Visibility timeout</strong>: the amount of time a task, received by a worker, is invisible to other workers; this should match the time of your longest-running task, including countdown, ETA and retry</p>
</li>
<li><p><strong>Delivery delay</strong>: when a new task is created, it remains invisible to all workers for the time specified here</p>
</li>
<li><p><strong>Receive message wait time</strong>: controls the maximum amount of time that polling will wait for messages to become available to receive (long polling); if you want to minimise costs, set this to the maximum value (20s)</p>
</li>
<li><p><strong>Message retention period</strong>: the amount of time a message is retained on the queue; depends very much on what you do, eg if you have very long running once-a-day tasks 1-2 days might be appropriate, and a few minutes might be enough for many short running tasks</p>
</li>
<li><p><strong>Maximum message size</strong>: maximum size of a message</p>
</li>
</ul>
<p>There are additional settings for FIFO queues:</p>
<ul>
<li><p><strong>Content-based deduplication</strong>: when enabled, the message deduplication is based on content (as opposed to a unique message ID)</p>
</li>
<li><p><strong>High throughput FIFO queue</strong>: configures the FIFO queue for maximum throughput; without going too much into the details, this limits your choice on the deduplication scope;</p>
</li>
<li><p><strong>Deduplication scope</strong> and <strong>FIFO throughput limit</strong>: message deduplication and throughput limits can be configured either per queue or per message group within a queue (based on a message group ID)</p>
</li>
</ul>
<p>SQS provides in-transit encryption by default. This means that messages are encrypted while being sent from the producer to SQS and down to the Celery worker.</p>
<p>To add at-rest encryption to your queue (ie message encryption while in the queue), enable server-side encryption. Unless you know what you do (I don’t), go with the Amazon SQS key (SSE-SQS) default option.</p>
<p>Now the painful part: Access Policy. This very much depends on your requirements. Assuming you want to give every user in your AWS account access to all SQS actions on your queue (a very big assumption, please adjust as necessary), select the “Advanced” (JSON object) option and go with the default:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"Version"</span>: <span class="hljs-string">"2012-10-17"</span>,
  <span class="hljs-attr">"Id"</span>: <span class="hljs-string">"__default_policy_ID"</span>,
  <span class="hljs-attr">"Statement"</span>: [
    {
      <span class="hljs-attr">"Sid"</span>: <span class="hljs-string">"__owner_statement"</span>,
      <span class="hljs-attr">"Effect"</span>: <span class="hljs-string">"Allow"</span>,
      <span class="hljs-attr">"Principal"</span>: {
        <span class="hljs-attr">"AWS"</span>: <span class="hljs-string">"..."</span>
      },
      <span class="hljs-attr">"Action"</span>: [<span class="hljs-string">"SQS:*"</span>],
      <span class="hljs-attr">"Resource"</span>: <span class="hljs-string">"..."</span>
    }
  ]
}
</code></pre>
<p>The AWS access key and secret (which can be created and found in the AWS Management Console under IAM/Users) for a permissioned user will now give you access to the SQS queue.</p>
<p>In a production environment, much more fine-grained control would be adequate. For example, the Celery worker would be permissioned on ReadMessage and DeleteMessage actions. And the producer would be permissioned on SendMessage actions.</p>
<h2 id="heading-step-2-install-dependencies"><strong>Step 2: Install dependencies</strong></h2>
<p>You can find the code example on GitHub: <a target="_blank" href="https://aws.amazon.com/sqs/pricing/">https://github.com/bstiel/celery.school-sqs</a></p>
<p>Celery requires a few additional dependencies to work with SQS:</p>
<ul>
<li><p>boto3 (AWS SDK for Python)</p>
</li>
<li><p>pycurl (libcurl Python bindings)</p>
</li>
</ul>
<p>Install the additional packages individually or the complete Celery SQS bundle:</p>
<pre><code class="lang-bash">$ pip install <span class="hljs-string">'celery[sqs]'</span>
</code></pre>
<p>If you are on a Mac, chances are that you run into a pycurl issue. If you do, shoot me an email at <a target="_blank" href="https://aws.amazon.com/sqs/pricing/">bjoern.stiel@celery.school</a>.</p>
<h2 id="heading-step-3-configure-celery"><strong>Step 3: Configure Celery</strong></h2>
<p>To configure Celery, three things are required:</p>
<ul>
<li><p>AWS Access Key</p>
</li>
<li><p>AWS Secret Key</p>
</li>
<li><p>the SQS queue URL</p>
</li>
</ul>
<p>AWS Access Key and AWS Secret Key are attached to the corresponding IAM user. The SQS queue URL can be found in the AWS Management Console under SQS/Queues.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700652614702/8b124f09-a198-4e44-b88e-f8c59734c648.png" alt class="image--center mx-auto" /></p>
<p>By default, Celery creates queues automatically as they are being requested by the application logic. I prefer to have full control of this. To prevent this from happening, set <code>task_create_missing_queues</code> to <code>False</code>. And use <code>broker_transport_options.predefined_queues</code> to mirror the actual SQS queues that I created in step 1.</p>
<pre><code class="lang-Python"><span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

sqs_queue_url = <span class="hljs-string">"..."</span>
aws_access_key = <span class="hljs-string">"..."</span>
aws_secret_key = <span class="hljs-string">"..."</span>

app = Celery(
    <span class="hljs-string">"app"</span>,
    broker_url=<span class="hljs-string">f"sqs://<span class="hljs-subst">{aws_access_key}</span>:<span class="hljs-subst">{aws_secret_key}</span>@"</span>,
    broker_transport_options={
        <span class="hljs-string">"region"</span>: <span class="hljs-string">"us-east-1"</span>, <span class="hljs-comment"># your AWS SQS region</span>
        <span class="hljs-string">"predefined_queues"</span>: {
            <span class="hljs-string">"celery"</span>: {  <span class="hljs-comment">## the name of the SQS queue</span>
                <span class="hljs-string">"url"</span>: sqs_queue_url,
                <span class="hljs-string">"access_key_id"</span>: aws_access_key,
                <span class="hljs-string">"secret_access_key"</span>: aws_secret_key,
            }
        },
    },
    task_create_missing_queues=<span class="hljs-literal">False</span>,
)
</code></pre>
<h2 id="heading-step-4-run"><strong>Step 4: Run</strong></h2>
<p>Check out my GitHub repository: <a target="_blank" href="https://aws.amazon.com/sqs/pricing/">https://github.com/bstiel/celery.school-sqs</a> if you have not done so yet. Use honcho to start the producer and worker (defined in the Procfile) simultaneously:</p>
<pre><code class="lang-bash">
```bash
$ honcho start
</code></pre>
<pre><code class="lang-bash">13:36:41 system     | producer.1 started (pid=29441)
13:36:41 system     | worker.1 started (pid=29440)
13:36:42 worker.1   |
13:36:42 worker.1   |
13:36:42 worker.1   |
13:36:42 worker.1   | celery@** v5.3.0 (emerald-rush)
13:36:42 worker.1   |
13:36:42 worker.1   | [config]
13:36:42 worker.1   | .&gt; app:         app:0x102ec8c10
13:36:42 worker.1   | .&gt; transport:   sqs://**:**@localhost//
13:36:42 worker.1   | .&gt; results:     disabled://
13:36:42 worker.1   | .&gt; concurrency: 1 (solo)
13:36:42 worker.1   | .&gt; task events: OFF (<span class="hljs-built_in">enable</span> -E to monitor tasks <span class="hljs-keyword">in</span> this worker)
13:36:42 worker.1   |
13:36:42 worker.1   | [queues]
13:36:42 worker.1   | .&gt; celery           exchange=celery(direct) key=celery
13:36:42 worker.1   |
13:36:42 worker.1   |
13:36:42 worker.1   | [tasks]
13:36:42 worker.1   |   . do_something
13:36:42 worker.1   |
13:36:42 worker.1   | [2023-11-15 13:36:42,246: INFO/MainProcess] Connected to sqs://**:**@localhost//
13:36:42 worker.1   | [2023-11-15 13:36:42,784: INFO/MainProcess] celery@** ready.
13:36:42 producer.1 | INFO:__main__:203f94fa-6196-442c-ae17-1c4c3cda2966
13:36:43 worker.1   | [2023-11-15 13:36:43,233: INFO/MainProcess] Task do_something[203f94fa-6196-442c-ae17-1c4c3cda2966] received
13:36:43 worker.1   | [2023-11-15 13:36:43,238: WARNING/MainProcess] Message received
</code></pre>
<p>And that’s a full task round trip: producer =&gt; SQS =&gt; worker.</p>
<h1 id="heading-final-thoughts"><strong>Final thoughts</strong></h1>
<p>This article was all about helping you understand was SQS is and how to set it up as a Celery message broker.</p>
<p>In my experience, SQS is a reliable, highly available message broker and a real alternative to Redis and RabbitMQ. SQS can be a great choice, especially if your infrastructure is already on AWS.</p>
<p>There are more details to cover, especially around coordinating Celery and SQS configuration. If you have any questions on this, please reach out via email <a target="_blank" href="https://aws.amazon.com/sqs/pricing/">bjoern.stiel@celery.school</a> or comment below 👇.</p>
]]></content:encoded></item><item><title><![CDATA[Simple is Better Than Complex]]></title><description><![CDATA[My other job is being a partner in a bootstrapped SaaS business. Our product is a web app that brings GitHub-style visibility to Excel workbooks. Our users…]]></description><link>https://celery.school/simple-is-better-than-complex</link><guid isPermaLink="true">https://celery.school/simple-is-better-than-complex</guid><category><![CDATA[reflection]]></category><category><![CDATA[architecture]]></category><category><![CDATA[Complexity]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Tue, 07 Nov 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/l090uFWoPaI/upload/4731ff33bd08b70d3cc2b324beca69c8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>My other job is being a partner in a bootstrapped SaaS business. Our product is a web app that brings GitHub-style visibility to Excel workbooks.</p>
<p>Our users push their Excel workbooks to a GitHub repository. We mirror that GitHub repository and let our users browse and diff their workbook's content as if it wasn't a binary file.</p>
<p>At its core, the technical challenges are all about parsing Excel files (binaries) and serialising them into a bunch of Git-friendly text and JSON files.</p>
<p>Depending on the size and complexity of the Excel workbook, this is a slow task. Multiple Excel files per commit, multiple commits per push and multiple repositories only add to the problem.</p>
<p>We rely heavily on Celery for this. As a Git commit comes in, we offload the workload to a Celery task. The Celery task traverses the commit in search of any Excel files and parses them. It then rewrites the commit with the serialised Excel file content, replacing the original binary file.</p>
<h2 id="heading-the-root-of-all-problems"><strong>The root of all problems</strong></h2>
<p>In the early days of our product, I was fixated on optimising the time to process a commit. And so I deployed every trick in the Celery book. Parallelisation was my answer to everything.</p>
<p>The version we shipped to our first paying on-premise customer back in 2017 relied heavily on chains, groups and chords. It was fast. And it was complex.</p>
<p>It was so horribly complex that troubleshooting was literally finding that needle in a haystack.</p>
<p>My premature fixation on efficient processing not only led to a complex Celery workflow canvas. It also led to some design decisions that proved difficult to migrate away from as a bootstrapped startup with limited manpower.</p>
<h2 id="heading-simplify-all-the-things"><strong>Simplify all the things</strong></h2>
<p>Fast forward to 2023 (!) and through a combination of utter frustration and fortunate circumstances, we finally decided to reduce complexity and refactor. It took my business partner and me six months to tame the beast.</p>
<p>Our codebase now weighs 13,000 lines of code less. What used to be a complex Celery workflow, made up of over ten tasks, is now a simple single task. Task progress is now easy to follow, troubleshoot and feedback to the user via the UI.</p>
<p>When something goes wrong, I have a pretty good idea of where to start looking. What used to cost me hours (not including the time I procrastinated because of the pure thought of the horror that was to come), is now down to ten minutes most of the time.</p>
<p>Does processing an Excel file now take longer? Yes, it does. But as it turns out, a good UI experience makes more than up for it.</p>
<h2 id="heading-lessons-learned"><strong>Lessons learned</strong></h2>
<p>Here are my lessons learned, even though they all sound like clichés:</p>
<ul>
<li><p>stick with a simple Celery workflow canvas</p>
</li>
<li><p>avoid groups and chords if you can</p>
</li>
<li><p>if you think you cannot avoid groups and chords, think again</p>
</li>
<li><p>beware of "design spills" when using complex Celery primitives</p>
</li>
<li><p>decide on your app workflow first, then on your Celery implementation</p>
</li>
</ul>
<p>PS: Our old Vue.js frontend is gone as well. We replaced it with htmx, but that's another story for another day.</p>
]]></content:encoded></item><item><title><![CDATA[Celery Execution Pools: What is it all about?]]></title><description><![CDATA[Have you ever asked yourself what happens when you start a Celery worker? Ok, it might not have been on your mind. But you might have come across things…]]></description><link>https://celery.school/celery-worker-pools</link><guid isPermaLink="true">https://celery.school/celery-worker-pools</guid><category><![CDATA[worker pool]]></category><category><![CDATA[celery]]></category><category><![CDATA[multiprocessing]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Thu, 19 Oct 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/QGdRrty4054/upload/8996d52221fbc77a718379f9d299f598.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever asked yourself what happens when you start a Celery worker? Ok, it might not have been on your mind. But you might have come across things like execution pool, concurrency settings, prefork, threads, <a target="_blank" href="https://celery.school/gevent-vs-prefork-performance">gevent</a>, eventlet and solo. So, what is it all about? How does it all fit together? And how is it related to the mechanics of a Celery worker?</p>
<h2 id="heading-the-celery-worker"><strong>The Celery worker</strong></h2>
<p>When you start a Celery worker on the command line via <code>celery --app=...</code>, you just start a supervisor process. The Celery worker itself does not process any tasks (with one notable exception, which I will get to later).</p>
<p>It spawns child processes (or threads) and deals with all the bookkeeping stuff. The child processes (or threads) execute the actual tasks. These child processes (or threads) are also known as the <em>execution pool</em>.</p>
<p>The size of the execution pool determines the number of tasks your Celery worker can process. The more processes (or threads) the worker spawns, the more tasks it can process concurrently. If you need to process as many tasks as quickly as possible, you need a bigger execution pool. At least, that is the idea.</p>
<p>In reality, it is more complicated. The answer to the question of how big your execution pool should be depends on whether you use processes or threads. And the answer to that question depends what your tasks do.</p>
<h2 id="heading-the-pool-option"><strong>The --pool option</strong></h2>
<p>You can choose between processes or threads, using the <code>--pool</code> command line argument. Use a <a target="_blank" href="https://celery.school/celery-gevent-5-lessons-learned">gevent execution pool</a>, spawning 100 "green threads" or "greenlets" (you need to pip-install gevent first):</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker with the gevent pool</span>
$ celery worker --app=worker.app --pool=gevent --concurrency=100
</code></pre>
<p>Don't worry too much about the details for now (why are threads <em>green</em>?). We will go into more details if you carry on reading. Celery supports four execution pool implementations:</p>
<ul>
<li><p>prefork</p>
</li>
<li><p>threads</p>
</li>
<li><p>solo</p>
</li>
<li><p>eventlet</p>
</li>
<li><p>gevent</p>
</li>
</ul>
<p>The <code>--pool</code> command line argument is optional. If not specified, Celery defaults to the prefork execution pool.</p>
<h2 id="heading-prefork"><strong>Prefork</strong></h2>
<p>The prefork pool implementation is based on Python's multiprocessing package. It allows your Celery worker to side-step Python's Global Interpreter Lock and fully leverage multiple processors on a given machine.</p>
<p>You want to use the prefork pool if your tasks are CPU-bound. A task is CPU-bound, if it spends the majority of its time using the CPU (crunching numbers). Your task could only go faster if your CPU were faster.</p>
<p>The number of available cores limits the number of concurrent processes. It only makes sense to run as many CPU-bound tasks in parallel as there are CPUs available.</p>
<p>This is why Celery defaults to the number of CPUs available on the machine if the <code>--concurrency</code> argument is not set. Start a worker using the prefork pool, using as many processes as there are CPUs available:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker with the prefork pool</span>
$ celery worker --app=worker.app
</code></pre>
<h2 id="heading-threads"><strong>Threads</strong></h2>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker with the threads pool</span>
$ celery worker --app=worker.app --pool=threads
</code></pre>
<p>The threads pool is Celery's latest addition to the pool zoo and was introduced back in 2019. It uses Python's ThreadPoolExecutor. These threads are real OS threads, managed directly by the operating system kernel.</p>
<p>The threads pool does what it says on the tin and is suitable for tasks that are I/O bound. A task is I/O bound if it spends the majority of its time waiting for an Input/Output operation to finish. Your task could only go faster if the Input/Output operation were faster.</p>
<p>Just like in the prefork case, Celery defaults to the number of CPUs available on the machine if no <code>--concurrency</code> is specified. This behaviour is slightly misleading because Python's Global Interpreter Lock (GIL) still reigns. Even if you have 4 CPUs and have Celery spawn 4 worker threads, only one thread can execute Python bytecode at any given time.</p>
<h2 id="heading-solo"><strong>Solo</strong></h2>
<p>The solo pool is a bit of a special execution pool. Strictly speaking, the solo pool is neither threaded nor process-based. More strictly speaking, the solo pool is not even a pool as it is always solo. Even more strictly speaking, the solo pool contradicts the principle that the worker does not process any tasks.</p>
<p>The solo pool runs inside the worker process. It runs <em>inline</em> which means there is no bookkeeping overhead. This makes the solo worker fast. But it also blocks the worker during task execution. Which has some implications when remote-controlling workers.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker in solo mode</span>
$ celery worker --app=worker.app --pool=solo
</code></pre>
<p>The solo pool is an interesting option when running CPU-intensive tasks in a microservices environment. For example, in a Kubernetes context, managing the worker pool size can be easier than managing multiple execution pools. Instead of managing the execution pool size per worker(s), you manage the total number of workers.</p>
<h2 id="heading-eventlet-and-gevent"><strong>Eventlet and gevent</strong></h2>
<p>Let's say you need to execute thousands of HTTP GET requests to fetch data from external REST APIs. The time it takes to complete a single GET request depends almost entirely on the time it takes the server to handle that request. Most of the time, your tasks wait for the server to send the response, not using any CPU.</p>
<p>The bottleneck for this kind of task is not the CPU. The bottleneck is waiting for an Input/Output operation to finish. This is an Input/Output-bound task (I/O bound). The time the task takes to complete is determined by the time spent waiting for an input/output operation to finish.</p>
<p>If you run a single process execution pool, you can only handle one request at a time. It takes a long time to complete those thousands of GET requests. So you spawn more processes.</p>
<p>However, there is a tipping point where adding more processes to the execution pool hurts performance. The overhead of managing the process pool becomes more expensive than the marginal gain for an additional process.</p>
<p>In this scenario, spawning hundreds (or even thousands) of threads is a much more efficient way to increase capacity for I/O-bound tasks. Celery supports two thread-based execution pools: eventlet and gevent. Here, the execution pool runs in the same process as the Celery worker itself. To be precise, both eventlet and gevent use greenlets and not threads.</p>
<p>Greenlets - also known as green threads, cooperative threads or coroutines - give you threads, but without using threads (unlike the threads pool). Threads are managed by the operating system kernel. The operating system uses a general-purpose scheduler to switch between threads. This general-purpose scheduler is not always very efficient.</p>
<p>Greenlets emulate multi-threaded environments without relying on any native operating system capabilities. Greenlets are managed in application space and not in kernel space. There is no scheduler pre-emptively switching between your threads at any given moment. Instead, your greenlets voluntarily or explicitly give up control to one another at specified points in your code.</p>
<p>This makes greenlets excel at running a huge number of non-blocking tasks. Your application can schedule things much more efficiently. For a large number of tasks, this can be a lot more scalable than letting the operating system interrupt and awaken threads arbitrarily.</p>
<p>For us, the benefit of using a gevent or eventlet pool is that our Celery worker can do more work than it could before. This means we do not need as much RAM to scale up. This optimises the utilisation of our workers.</p>
<p>Start a Celery worker using a gevent execution pool with 500 worker threads (you need to pip-install gevent):</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker using the gevent pool</span>
$ celery worker --app=worker.app --pool=gevent --concurreny=500
</code></pre>
<p>Start a Celery worker using a eventlet execution pool with 500 worker threads (you need to pip-install eventlet):</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker using the eventlet pool</span>
$ celery worker --app=worker.app --pool=eventlet --concurreny=500
</code></pre>
<p>Both pool options are based on the same concept: Spawn a greenlet pool. The difference is that --pool=gevent uses the gevent Greenlet pool  (gevent.pool.Pool). Whereas --pool=eventlet uses the eventlet Greenlet pool (eventlet.GreenPool).</p>
<p><a target="_blank" href="http://www.gevent.org/?ref=celery-school.ghost.io">gevent</a> and <a target="_blank" href="http://eventlet.net/?ref=celery-school.ghost.io">eventlet</a> are both packages that you need to pip-install yourself. There are implementation differences between the eventlet and gevent packages. Depending on your circumstances, one can perform better than the other. On the downside, both packages rely on monkey patching. This has an impact on package compatibility and your code base.</p>
<h2 id="heading-the-concurrency-option"><strong>The --concurrency option</strong></h2>
<p>To choose the best execution pool, you need to understand whether your tasks are CPU- or I/O-bound. CPU-bound tasks are best executed by a prefork execution pool. I/O bound tasks are best executed by a gevent/eventlet execution pool.</p>
<p>The only question that remains is: how many worker processes/threads should you start? The <code>--concurrency</code> command line argument determines the number of processes/threads:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker using the prefork pool</span>
$ celery worker --app=worker.app --concurrency=2
</code></pre>
<p>This starts a worker with a prefork execution pool which is made up of two processes. For prefork pools, the number of processes should not exceed the number of CPUs.</p>
<p>Spawn a Greenlet based execution pool with 500 worker threads:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker using the gevent pool</span>
$ celery worker --app=worker.app --pool=gevent --concurrency=500
</code></pre>
<p>If the <code>--concurrency</code> argument is not set, Celery always defaults to the number of CPUs, whatever the execution pool.</p>
<p>This makes the most sense for the prefork execution pool. But you have to take it with a grain of salt. If there are many other processes on the machine, running your Celery worker with as many processes as CPUs available might not be the best idea.</p>
<p>Using the default concurrency setting for a gevent/eventlet pool is almost outright stupid. The number of green threads it makes sense for you to run is unrelated to the number of CPUs you have at your disposal.</p>
<p>Another special case is the solo pool. Even though you can provide the <code>--concurrency</code> command line argument, is meaningless for this execution pool.<br />For these reasons, it is always a good idea to set the <code>--concurrency</code> command line argument.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Celery supports three concepts for spawning its execution pool: Prefork, OS Threads and Greenlets. Prefork is based on multiprocessing and is the best choice for tasks which make heavy use of CPU resources. Prefork pool sizes are roughly in line with the number of available CPUs on the machine.</p>
<p>Tasks that perform Input/Output operations should run in a thread or greenlet-based execution pool.</p>
<p>The threads pool uses OS threads and plays nicely with any codebase. There is a limit though on how many threads it makes sense to spawn.</p>
<p>Greenlets behave like threads but are much more lightweight and efficient. Greenlet pools can scale to hundreds or even thousands of tasks. Using one of the greenlet implementations will in all likelihood have an impact on your codebase.</p>
<p>What can you do if you have a mix of CPU and I/O-bound tasks? Set up two queues with one worker processing each queue. One queue/worker with a prefork execution pool for CPU-heavy tasks. And another queue/worker with a gevent or eventlet execution pool for I/O tasks. And don't forget to route your tasks to the correct queue.</p>
]]></content:encoded></item><item><title><![CDATA[Python Podcast Picks: My Favourites]]></title><description><![CDATA[I took this photo shortly after dawn somewhere in Norfolk, England. I was a bit over 24 hours into a 680km gravel race and listening to Brian Okken…]]></description><link>https://celery.school/python-podcasts-and-ultra-distance-cycling</link><guid isPermaLink="true">https://celery.school/python-podcasts-and-ultra-distance-cycling</guid><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Wed, 18 Oct 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700512644990/19c5c7e2-04ec-4c18-a6fe-048c562b0893.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I took this photo shortly after dawn somewhere in Norfolk, England. I was a bit over 24 hours into a 680km gravel race and listening to Brian Okken interviewing Mariatta Wijaya on Brian's podcast Python People.</p>
<p>I am into self-supported, multi-day (gravel) cycle rides with 20 hours a day in the saddle and very little sleep.</p>
<p>Physiologically, I spend most of the time in heart rate zone 2 (around 65%-75% of my max heart rate).</p>
<p>That's where my body can sustain the effort, and my brain is still functional to deal with navigational and mechanical problem-solving, self-talk - and Python podcasts!</p>
<p>Mostly uninterrupted time without access to a screen equates to perfect podcast time.</p>
<p>Here are my three Python podcast picks.</p>
<h2 id="heading-podcast-python-test"><strong>Podcast: Python Test</strong></h2>
<p><em>Python Test</em> (formerly known as <em>Test and Code</em>) is hosted by Brian Okken, author of <em>Python Testing with pytest</em>. It is mostly what it says on the tin and more.</p>
<p>Because tests are just an indicator of how maintainable code is, Brian's podcast touches upon a lot of other software engineering practices, such as automation, packaging, CI/CD, etc.</p>
<p>New episodes are released at varying intervals, ranging from weekly to monthly. There are currently more than 200 episodes available.</p>
<ul>
<li><a target="_blank" href="https://testandcode.com/?ref=celery-school.ghost.io">Python Test Podcast</a></li>
</ul>
<h2 id="heading-podcast-talk-python-to-me"><strong>Podcast: Talk Python To Me</strong></h2>
<p><em>Talk Python to Me</em> is a weekly podcast hosted by Michael Kennedy, Python Software Foundation Fellow and founder of <em>Talk Python Training</em>.</p>
<p><em>Talk Python to Me</em> episodes cover a wide range of Python and related topics.</p>
<p>As an HTMX fan, my favourite episode is <a target="_blank" href="https://talkpython.fm/episodes/show/321/htmx-clean-dynamic-html-pages?ref=celery-school.ghost.io">Episode 321: HTMX - Clean, Dynamic HTML Pages</a> with Carson Gross, creator of HTMX.</p>
<ul>
<li><a target="_blank" href="https://talkpython.fm/?ref=celery-school.ghost.io">Talk Python To Me Podcast</a></li>
</ul>
<h2 id="heading-podcast-python-people"><strong>Podcast: Python People</strong></h2>
<p>Launched in July 2023, this is Brian Okken's latest podcast venture. Yes, Brian Okken, the same guy who hosts the <em>Python Test</em> podcast. I don't know how he does it.</p>
<p>I like <em>Python People</em> because it is about the Python community and the human beings that are the fabric of this community.</p>
<p>New episodes are released at varying intervals. As I am writing this, I am eagerly awaiting the October 2023 episode.</p>
<ul>
<li><a target="_blank" href="https://pythonpeople.fm/?ref=celery-school.ghost.io">Python People Podcast</a></li>
</ul>
<p>Fun fact: Podcasts consume a lot less battery power on my wireless Shokz headphones compared to music!</p>
<div class="hn-embed-widget" id="mailerlite"></div>]]></content:encoded></item><item><title><![CDATA[The Prefork Worker Pool]]></title><description><![CDATA[The question of scaling - concurrency in Cerlery jargon - generally comes as an afterthought. And the pool choice is an afterthought of the afterthought…]]></description><link>https://celery.school/the-prefork-worker-pool</link><guid isPermaLink="true">https://celery.school/the-prefork-worker-pool</guid><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Mon, 25 Sep 2023 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/O3VIUojceNc/upload/82643c09c78916e3372501ac59dea9a4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The question of scaling - concurrency in Cerlery jargon - generally comes as an afterthought. And the pool choice is an afterthought of the afterthought.</p>
<p>Why do I start with the scaling question when I write about Celery's prefork pool?</p>
<p>Because the prefork pool is Celery's default. This means you are using the prefork pool even when you are not aware. It is easy to get started with, works with any Python package and plays nicely with whatever your code does. It so painfree that you do not have to think or worry about it.</p>
<p>Until you do, because you start looking into scaling. That is when the honeymoon period comes to an end and the prefork pool turns into a CPU und memory hungry, database connections spawning monster. With a serious impact on costs of running your app.</p>
<p>This is part three of my seven parts series about Celery execution pools: the prefork pool. I am going to cover what the prefork pool is, how it works, its configuration options, its limitations. The good and the bad. My goal is to help you make an educated decision whether the prefork pool is a good fit for your application.</p>
<h3 id="heading-what-is-prefork"><strong>What is prefork?</strong></h3>
<p>The term forking comes from the Linux and Unix world. <code>fork()</code> is an operating systems call and creates a new process by duplicating the calling process.</p>
<p>In server architectures, prefork is a model to handle multiple concurrent workload. At startup (pre), the server creates a number of child processes (forks). Multiple child processes can handle multiple tasks concurrently.</p>
<p>The child processes stay alive so that they are available for incoming workload. This allows the server to handle a higher workload, faster.</p>
<h3 id="heading-starting-a-celery-prefork-worker"><strong>Starting a Celery prefork worker</strong></h3>
<p>To start a Celery worker using the prefork pool, use the <code>prefork</code> or <code>processes</code> <code>--pool</code> option, or no pool option at all. Use <code>--concurrency</code> to control the number of child processes (forks) within the pool.</p>
<pre><code class="lang-bash">celery --app=worker.app worker --concurrency=2 --pool=prefork
celery --app=worker.app worker --concurrency=2 --pool=processes
celery --app=worker.app worker --concurrency=2
</code></pre>
<p>The worker clones itself and creates two new processes. This gives you three copies of your Celery app: the worker (parent) process and two forked (child) processes.</p>
<pre><code class="lang-bash">[config]
.&gt; app:         app:0x1027f3d50
.&gt; transport:   redis://localhost:6379/0
.&gt; results:     disabled://
.&gt; concurrency: 2 (prefork)
.&gt; task events: OFF (<span class="hljs-built_in">enable</span> -E to monitor tasks <span class="hljs-keyword">in</span> this worker)

[queues]
.&gt; celery           exchange=celery(direct) key=celery
</code></pre>
<p>The child processes do not share state. Neither do they not communicate with each other. They do not even know that they have siblings. The parent process (the worker) communicates with the pool processes via pipes. It is the worker's responsibility to pick new tasks from the broker, pass them on to the pool, collect results from the pool and write them to the result backend (if set up).</p>
<p>Because of the process isolation, Python's Global Interpreter Lock (GIL) works beautifully with the prefork pool. By being multiprocessing-based, it is pythonic concurrency by design.</p>
<p>This gives the prefork pool it's well behaved characteristics. It does not impose any rules on how you write your code. Nor does it restrict you on the Python packages you can use. This makes the prefork pool well-understood, stable and reliable. The prefork pool is a rock solid choice that is as pythonic as it gets.</p>
<h3 id="heading-configuration"><strong>Configuration</strong></h3>
<p>Celery provides a number of settings for the prefork pool. Some of which are only available to the prefork pool.</p>
<h3 id="heading-concurrency"><strong>Concurrency</strong></h3>
<p>The number of concurrent worker processes in the pool. Defaults to number of the number of CPUs on host machine if omitted.</p>
<ul>
<li><p>Worker command line argument: <code>--concurrency &lt;n&gt;</code></p>
</li>
<li><p>Environment variable: <code>CELERY_WORKER_CONCURRENCY=&lt;n&gt;</code></p>
</li>
<li><p>Celery app arguments: <code>Celery(worker_concurrency=&lt;n&gt;)</code></p>
</li>
<li><p>Celery config: <code>app.conf.worker_concurrency = &lt;n&gt;</code></p>
</li>
</ul>
<h3 id="heading-maximum-number-of-tasks-per-child"><strong>Maximum number of tasks per child</strong></h3>
<p>The maximum number of tasks <code>&lt;n&gt;</code> a pool process is allowed to execute before it is shutdown and replaced with a new me. Eg if set to ten, the worker shuts down a pool process after that process has executed ten tasks. It is then replaced with a new fork. Ugly but useful if you deal with memory leaks you have no control over. If not set, the process will just execute tasks for as long as it is alive.</p>
<ul>
<li><p>Worker command line argument: <code>--max-tasks-per-child &lt;n&gt;</code></p>
</li>
<li><p>Environment variable: <code>CELERY_WORKER_MAX_TASKS_PER_CHILD=&lt;n&gt;</code></p>
</li>
<li><p>Celery app arguments: <code>Celery(worker_max_tasks_per_child=&lt;n&gt;)</code></p>
</li>
<li><p>Celery config: <code>app.conf.worker_max_tasks_per_child = &lt;n&gt;</code></p>
</li>
</ul>
<p>Running with a max-tasks-per-child setting of three and a concurrency of one. The logs show that the worker shuts down ForkPoolWorker-1 after three tasks and replaces it with ForkPoolWorker-2. Note how tasks queue up while ForkPoolWorker-1 is shutting and ForkPoolWorker-2 is starting up.</p>
<pre><code class="lang-bash">[2023-09-18 14:31:18,924: INFO/MainProcess] Task worker.task1 received
[2023-09-18 14:31:18,925: INFO/ForkPoolWorker-1] Task worker.task1 succeeded
[2023-09-18 14:31:19,433: INFO/MainProcess] Task worker.task1 received
[2023-09-18 14:31:19,434: INFO/ForkPoolWorker-1] Task worker.task1 succeeded
[2023-09-18 14:31:19,942: INFO/MainProcess] Task worker.task1 received
[2023-09-18 14:31:19,944: INFO/ForkPoolWorker-1] Task worker.task1 succeeded
[2023-09-18 14:31:20,453: INFO/MainProcess] Task worker.task1 received
[2023-09-18 14:31:20,965: INFO/MainProcess] Task worker.task1 received
[2023-09-18 14:31:21,471: INFO/MainProcess] Task worker.task1 received
[2023-09-18 14:31:21,979: INFO/MainProcess] Task worker.task1 received
[2023-09-18 14:31:22,126: INFO/ForkPoolWorker-2] Task worker.task1 succeeded
[2023-09-18 14:31:22,130: INFO/ForkPoolWorker-2] Task worker.task1 succeeded
</code></pre>
<h3 id="heading-maximum-memory-per-child"><strong>Maximum memory per child</strong></h3>
<p>Similar to the maximum number of tasks <code>&lt;n&gt;</code> per child, but based on resident memory usage. When the maximum amount of resident memory (in kb) is reached, the child process is shut down after processing its current task and replaced by a new process.</p>
<ul>
<li><p>Worker command line argument: <code>--max-memory-per-child &lt;n&gt;</code></p>
</li>
<li><p>Environment variable: <code>CELERY_WORKER_MAX_MEMORY_PER_CHILD=&lt;n&gt;</code></p>
</li>
<li><p>Celery app arguments: <code>Celery(worker_max_memory_per_child=&lt;n&gt;)</code></p>
</li>
<li><p>Celery config: <code>app.conf.worker_max_memory_per_child = &lt;n&gt;</code></p>
</li>
</ul>
<h3 id="heading-autoscaling-pool-size"><strong>Autoscaling pool size</strong></h3>
<p>The autoscale option resizes the pool based on load. It adds pool processes, up to a maximum concurrency of<code>&lt;n&gt;</code>, when there is work to do. It removes processes down to a minimum pool size of <code>&lt;m&gt;</code> when the workload is low.</p>
<ul>
<li><p>Worker command line argument: <code>--autoscale &lt;m&gt;,&lt;n&gt;</code></p>
</li>
<li><p>Environment variable: <code>CELERY_WORKER_AUTOSCALE=&lt;m&gt;,&lt;n&gt;</code></p>
</li>
<li><p>Celery app arguments: <code>Celery(worker_max_memory_per_child=&lt;n&gt;)</code></p>
</li>
<li><p>Celery config: <code>app.conf.worker_max_memory_per_child = &lt;n&gt;</code></p>
</li>
</ul>
<p>Running with a an autoscale setting of 1,3. As tasks start queueing up, the worker adds a new process to the pool.</p>
<pre><code class="lang-bash">[2023-09-19 11:45:08,708: INFO/MainProcess] Task worker.task1 received
[2023-09-19 11:45:08,711: INFO/MainProcess] Task worker.task1 received
[2023-09-19 11:45:08,712: INFO/MainProcess] Scaling up 1 processes.
[2023-09-19 11:45:08,713: INFO/ForkPoolWorker-1] Task worker.task1 succeeded
[2023-09-19 11:45:08,731: INFO/MainProcess] Task worker.task1 received
[2023-09-19 11:45:08,732: INFO/ForkPoolWorker-1] Task worker.task1 succeeded
[2023-09-19 11:45:08,737: INFO/ForkPoolWorker-2] Task worker.task1 succeeded
</code></pre>
<p>When using the autoscale option, inconsistencies can occur. In this case, for the minimum pool size, the concurrency setting takes precedence over the minimum autoscale setting. For example, when you run with a concurrency of two and an autoscale of (1,3), the pool scales up to three but not down below two. When you run with a concurrency of two and an autoscale of (3, 4), the pool scales up to four and down to two.</p>
<h3 id="heading-the-good"><strong>The good</strong></h3>
<p>The prefork pool has a very pythonic look and feel because it works very much like Python's multiprocessing Pool class. Though Celery does not use Python's multiprocessing module but its own fork <a target="_blank" href="https://github.com/celery/billiard?ref=celery-school.ghost.io">billiard</a>, it is very similar.</p>
<p>The prefork pool plays perfectly with Python's Global Interpeter Lock (GIL). In simple terms, the GIL allows only one thread to execute Python code at a time, even on multi-core processors. To take full advantage of multi-core processors, you need to use multiple processes in Python. For that reason, the prefork pool shines when you deal with a CPU bound workload.</p>
<p>The process isolation also means that there are no rules on how you write your code. Think about how you need to refactor your code when moving from classic sync Python to an eventloop based async/await paradigm. There is nothing like that with the prefork pool. It also does not restrict you on the Python packages you can use.</p>
<h3 id="heading-the-bad"><strong>The bad</strong></h3>
<p>You cannot spawn another process from within a child process. This means that you cannot make use of multiprocessing inside a Celery task when using the prefork pool.</p>
<p>The biggest issue with the prefork pool is its impact on resources. It can becomoe very hungry. For one, there is memory consumption. Total resident memory consumption is roughly the resident memory footprint of your application x (concurrency + 1). The +1 being the worker (parent) process.</p>
<p>Then there is the impact on CPU usage. Remember that it is one CPU per child. If you have a concurrency of 10, you need 11 CPUs. The pool size is effectively limited by the number of CPUs at your disposal, or the $$$ you are willing to pay to your cloud provider.</p>
<p>The actual issue is more nuanced though. For example, if your tasks perform heavy calculations and require CPU, you are putting those 11 CPUs to good use. If all you do is hitting an external API or reading and writing large files to disk, you are waisting CPU cycles and ultimately $$$.</p>
<p>Imagine a Celery app that fetches large image files from an external service and writes them to S3. Each transfer takes five seconds to complete and you get one request per second. To avoid any waiting time in the queue, you need to be able to process five requests a second concurrently.</p>
<p>You set your concurrency to five and pay for five Heroku dynos. But think about what your five fork processes do: they just sit there idling, not utilising any CPU resources. They copy a file from one place to another. Which is entirely IO bound and not a good use of CPU.</p>
<p>Five processes is not a lot, and neither is paying for five Heroku dynos. You can easily scale this example up to a higher throughput and longer running tasks and see that this is not a cost-effective solution. There are pool types that are much better suited for IO bound tasks and I will cover them as part of this series.</p>
<p>Another thing to bear in mind is database connections. Each fork process has its own database connection. If you have a concurrency of 10, you have 10 database connections. This is not a problem if you use a database connection pool. But if you do not, you are going to run into issues with the number of database connections you can open. There are ways to mitigate this, such as using a connection pooling service that sits outside your app, for example pgbouncer in the Postgres case.</p>
<h3 id="heading-closing-words"><strong>Closing words</strong></h3>
<p>While Celery's prefork pool is Celery's default and Python's darling, it is not a one size fits all solution. As a result, it is important to have at least an idea about workload requirements early on in the development process. In short: prefork and CPU yay, IO nay.</p>
]]></content:encoded></item><item><title><![CDATA[The Solo Worker Pool]]></title><description><![CDATA[Have you ever used the Celery solo execution pool? Don't worry if not, you are in good company. The solo pool is probably the most overlooked and…]]></description><link>https://celery.school/the-solo-worker-pool</link><guid isPermaLink="true">https://celery.school/the-solo-worker-pool</guid><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Thu, 03 Aug 2023 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/MSeS-X3Av2E/upload/af96e07ab3c5d98171ebaa9ab818c5c5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever used the Celery solo execution pool? Don't worry if not, you are in good company. The solo pool is probably the most overlooked and underrated of all Celery built-in execution pools. I can only speculate as to why it is overlooked, so I focus on why I think it is underrated. The solo pool is - and I am quoting the <a target="_blank" href="https://docs.celeryq.dev/en/latest/internals/reference/celery.concurrency.solo.html?ref=celery-school.ghost.io">Celery docs</a> here:</p>
<ul>
<li><p>blocking</p>
</li>
<li><p>inline</p>
</li>
<li><p>fast</p>
</li>
</ul>
<p>The keyword here is <code>inline</code>. Remember how <a target="_blank" href="https://celery-school.ghost.io/posts/celery-pool-types-part-1-the-worker-and-the-pool">the worker and the pool are two separate concerns</a>? While it does not mean that the worker and pool have to run in separate processes or threads, most pool implementations do precisely that to support the concurrent execution of tasks within the pool.</p>
<p>Inline means that the worker directly invokes the task code. The task code runs in the same process and thread as the worker itself. No forking, threading or event-looping. The worker simply invokes the task, just like any other Python function call.</p>
<p>The separation of concerns design pattern is still adhered to. That function call still goes through the different layers and interfaces that allow the worker to be agnostic about the actual pool type.</p>
<p>Everything runs in the same process, in the same thread. No process or thread management is required, no overhead between receiving the task and running it. This makes the solo pool as fast as it gets.</p>
<h3 id="heading-in-task-multiprocessing"><strong>In-task multiprocessing</strong></h3>
<p>Another benefit of the solo pool's simplicity is that there are no restrictions when it comes to the use of multiprocessing or multithreading within a task. For example, if you try to do multiprocessing within a Celery task, using the default prefork pool:</p>
<pre><code class="lang-Python"><span class="hljs-comment"># worker.py</span>
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> concurrent.futures <span class="hljs-keyword">import</span> ProcessPoolExecutor
<span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

app = Celery(broker_url=os.environ[<span class="hljs-string">"CELERY_BROKER_URL"</span>])

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">square</span>(<span class="hljs-params">num</span>):</span>
    <span class="hljs-keyword">return</span> num * num


<span class="hljs-meta">@app.task(name="task1")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">task1</span>():</span>
    numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]

    <span class="hljs-keyword">with</span> ProcessPoolExecutor(max_workers=<span class="hljs-number">4</span>) <span class="hljs-keyword">as</span> pool:
        results = [pool.submit(square, i) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> numbers]
        squared_numbers = [result.get() <span class="hljs-keyword">for</span> result <span class="hljs-keyword">in</span> results]
        print(squared_numbers)
</code></pre>
<p>And run the worker using the prefork pool:</p>
<pre><code class="lang-bash">$ celery --app=worker.app worker --concurrency=1 --pool=prefork
</code></pre>
<p>You end up with a stack trace like this:</p>
<pre><code class="lang-bash">AssertionError: daemonic processes are not allowed to have children
[2023-07-25 17:33:51,965: ERROR/ForkPoolWorker-1]
Task task1[99acf138-c79f-4fb3-874c-cad56d725677]raised unexpected:
AssertionError(<span class="hljs-string">'daemonic processes are not allowed to have children'</span>)
...
File <span class="hljs-string">"/usr/local/lib/python3.10/multiprocessing/process.py"</span>, line 118, <span class="hljs-keyword">in</span> start
assert not _current_process._config.get(<span class="hljs-string">'daemon'</span>), \
AssertionError: daemonic processes are not allowed to have children
</code></pre>
<p>The issue is that the prefork pool itself is a forked process, even if you run it with a concurrency setting of one. And so that all child processes are terminated gracefully, daemonic processes cannot have children. I will go into more details in the next blog post of this series which is dedicated to the prefork pool.</p>
<p>This limitation does not exist for the solo pool as it runs in the same process as the worker itself. Changing the <code>--pool</code> argument to <code>solo</code> makes the task execute without issues, using multiprocessing within it.</p>
<pre><code class="lang-bash">$ celery --app=worker.app worker --pool=solo
</code></pre>
<h3 id="heading-scaling"><strong>Scaling</strong></h3>
<p>There is a downside to all this simplicity: no concurrency. The solo pool can only process one task at a time and the worker is blocked while the solo pool executes a task.</p>
<p>This requires a different scaling strategy to give your Celery cluster the ability multiple tasks concurrently. For example, instead of running a single worker with a prefork pool and a pool size (concurrency) of ten, run ten workers with a solo pool each. In both cases, you end you with a cluster concurrency of ten.</p>
<p>I hope you have enjoyed learning more about the solo pool and where it shines. If you have any questions, comment below 👇 or drop me an email <a target="_blank" href="http://mailto:bjoern.stiel@celery.school">bjoern.stiel@celery.school</a>.</p>
]]></content:encoded></item><item><title><![CDATA[The Worker and the Pool]]></title><description><![CDATA[Which pool type should you use? Does it have any implications for your code base? Why do certain aspects of your app work with one pool but fail with…]]></description><link>https://celery.school/the-worker-and-the-pool</link><guid isPermaLink="true">https://celery.school/the-worker-and-the-pool</guid><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Wed, 05 Jul 2023 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/sYK-jN0sKBY/upload/1b4b6e4febe102034da4ebdabb2d2adb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Which pool type should you use? Does it have any implications for your code base? Why do certain aspects of your app work with one pool but fail with another? What is the best scaling strategy?</p>
<p>Discussing the Celery execution pool topic in earnest requires some space. I am launching a series of articles on this, each article dedicated to one pool. The focus is on the inner workings, benefits, limitations and use cases of <a target="_blank" href="https://celery.school/celery-worker-pools">each pool type</a>. My goal is to equip you with the knowledge to make the right choice.</p>
<p>Here is the roadmap for the next couple of weeks. Kicking off with a rundown of the Celery worker, the pool and their relationship in this blog post:</p>
<ul>
<li><p>Part 1: The worker and the pool: Separation of concerns</p>
</li>
<li><p><a target="_blank" href="https://celery.school/posts/celery-pool-types-part-2-the-solo-pool/">Part 2: Keep it simple, stupid: The solo pool</a></p>
</li>
<li><p><a target="_blank" href="https://celery.school/posts/celery-pool-types-3-prefork/">Part 3: The default of all pools: Understanding the Prefork pool</a></p>
</li>
<li><p>Part 4: The not so new-ish kid on the block: The threads pool</p>
</li>
<li><p>Part 5: Coroutines all the way: The gevent and the eventlet pools</p>
</li>
<li><p>Part 6: How to choose the right pool for the right job</p>
</li>
<li><p>Part 7: Bonus: How to roll your custom pool</p>
</li>
</ul>
<h2 id="heading-worker"><strong>Worker</strong></h2>
<p>What exactly does the Celery worker do and how does it relate to the execution pool (aka worker pool or just pool)? Remember, Celery is made up of three building blocks:</p>
<ul>
<li><p>Producer: this is where a task gets scheduled for asynchronous execution, for example <code>task1.s(a=1, b=2).delay()</code> in a Django app</p>
</li>
<li><p>Message Broker: this is the storage the producer writes the serialized task to (think json, though it could be another format): Redis, RabbitMQ, Amazon SQS, Zookepper or simply the file system</p>
</li>
<li><p>Worker: this is a separate process that subscribes to new messages on the message broker and executes them</p>
</li>
</ul>
<p>The producer sends the task across to the message broker (the name of the task and its arguments). The Celery worker subscribes to the message broker. When the message broker notifies the worker of a new task, the worker pool executes the task, taking into account said arguments: The execution pool runs tasks, the worker runs the execution pool.</p>
<p>What is the point of this separation? It is the overhead unrelated to task execution: things like broker connectivity, handling disconnects, reconnects, retries, communication with other Celery workers, broadcasting events, configuration, logging, error handling etc.</p>
<h2 id="heading-execution-pool"><strong>Execution pool</strong></h2>
<p>Task execution is all about… 🥁 executing tasks. A task, in its serialised form (task name, args and kwargs), is written to the message broker. The message broker notifies the worker, the worker collects the task details and marks the task as reserved to prevent it being picked up by another worker. Finally, the worker runs the task code via the execution pool (and deals with result or error handling).</p>
<p>As multiple tasks come in via the message broker, there is a design decision to be made as to how to process these tasks. Some options that come to mind:</p>
<ul>
<li><p>process one task at a time, each task blocking until it has finished executing</p>
</li>
<li><p>process multiple tasks concurrently, using threading</p>
</li>
<li><p>process multiple tasks concurrently, using multiprocessing</p>
</li>
<li><p>process multiple tasks concurrently, with the help of coroutines</p>
</li>
</ul>
<p>Not so coincidentally, these options map one-to-one to the different Celery worker pool type implementations, which I am covering in the upcoming articles of this series:</p>
<ul>
<li><p>the solo pool: one task at a time, blocking</p>
</li>
<li><p>the threads pool: concurrent thread pool based task execution</p>
</li>
<li><p>the prefork pool: concurrent task execution based on multiprocessing</p>
</li>
<li><p>the gevent and eventlet pools: concurrent task execution using greenlets (coroutines)</p>
</li>
</ul>
<p>Where concurrent task execution is supported (all bar the solo pool), the number of concurrent processes, threads or coroutines is controlled by the <code>--concurrency</code> argument.</p>
<h2 id="heading-basepool"><strong>BasePool</strong></h2>
<p>Before turning your attention to the solo pool type, I would like to introduce you the Celery BasePool <a target="_blank" href="https://github.com/celery/celery/blob/main/celery/concurrency/base.py">BasePool</a> class first. Every execution pool implementation inherits from BasePool. Understanding some ideas of the BasePool class is a neat way to understand how the worker interacts with the execution pool.</p>
<p>Remember, when you start a Celery worker, you choose a pool via the <code>--pool</code> option. If you do not choose a pool, Celery chooses one for you (the prefork pool):</p>
<pre><code class="lang-bash">$ celery --app worker.app worker --pool prefork|threads|gevent|eventlet|solo
</code></pre>
<p>As the worker starts up, it creates an instance of the selected pool class. As long as the worker is up and running, it holds a reference to this pool instance. The pool class inherits from the BasePool, so the worker interacts with the pool instance via the methods defined in the BasePool class.</p>
<p>What happens when a new task comes in?</p>
<ul>
<li><p>the worker invokes <a target="_blank" href="https://github.com/celery/celery/blob/main/celery/worker/worker.py">WorkerController._process_task</a></p>
</li>
<li><p>…which in turn invokes <a target="_blank" href="https://github.com/celery/celery/blob/main/celery/worker/request.py">request.execute_using_pool</a></p>
</li>
<li><p>…which in turn invokes the pool method <a target="_blank" href="https://github.com/celery/celery/blob/main/celery/worker/request.py">pool.apply_async</a></p>
</li>
<li><p>…which in turn invokes the pool method <a target="_blank" href="https://github.com/celery/celery/blob/main/celery/concurrency/base.py">on_apply</a></p>
</li>
</ul>
<p>There are two takeaways from this: first off, there is a chain of events that is triggered when the worker receives a new task. This chain ends with a pool’s <code>on_apply</code> callback. This is where the action happens. Secondly, if you want to understand how different pool implementations work, the <code>on_apply</code> method is where you should poke about. And this is what I will be doing in the next articles of this series, starting with the solo pool.</p>
]]></content:encoded></item><item><title><![CDATA[Celery Config With Environment Variables]]></title><description><![CDATA[I am a strong proponent of strict separation of config from code. This means that my preferred app configuration is via environment variables (env vars)…]]></description><link>https://celery.school/celery-config-env-vars</link><guid isPermaLink="true">https://celery.school/celery-config-env-vars</guid><category><![CDATA[Celery config]]></category><category><![CDATA[celery]]></category><category><![CDATA[Environment variables]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Mon, 13 Mar 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/7cc4Zi_L3x0/upload/b12df5a0af2d90d3f7c43fd425a951be.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I am a strong proponent of strict separation of config from code. This means that my preferred app configuration is via environment variables (env vars).</p>
<p>Env vars are easy to change between deploys. They do not require code changes. Env vars are language and operating system agnostic. And there is little risk of env vars being checked into code repos - unlike config files.</p>
<p>Unfortunately, this is where Celery fails me. It encourages the use of <a target="_blank" href="https://docs.celeryq.dev/en/stable/userguide/configuration.html?ref=celery-school.ghost.io">configuration files</a>. Though certain settings can be controlled via env vars, others cannot. And the docs are not very transparent as to which settings fall into which category.</p>
<p>This has been a recurring frustration for me over the past years. My typical workaround would usually be something like this:</p>
<pre><code class="lang-python"><span class="hljs-comment"># celeryconfig.py</span>
<span class="hljs-keyword">import</span> json

broker_url = os.environ[<span class="hljs-string">"CELERY_BROKER_URL"</span>]
task_serializer = os.getenv(<span class="hljs-string">"CELERY_TASK_SERIALIZER"</span>, <span class="hljs-string">"json"</span>)
accept_content = json.loads(os.getenv(<span class="hljs-string">"CELERY_ACCEPT_CONTENT"</span>, <span class="hljs-string">"[\"json\"]"</span>))

<span class="hljs-comment"># more settings</span>
</code></pre>
<p>A few notes here:</p>
<ul>
<li><p><code>CELERY_BROKER_URL</code> is available as an env var to Celery and does not need to be specified here. But I do like all settings in one place.</p>
</li>
<li><p>Celery's <code>accept_content</code> expects a list. Env vars are strings, hence the <code>json.loads</code> trick to parse the string as a list.</p>
</li>
<li><p>Some of my settings mandatory, others are optional with a (my) default value. Another (more sensible) approach is to let Celery handle the default value by not setting it. I do it the way I do it so I have everything in one place.</p>
</li>
</ul>
<p>The other day I found myself implementing the same workaround again for a new Celery project. As my frustration grew once again, I started tossing around a more generic approach: expose all Celery settings via env vars.</p>
<p>Any environment variable prefixed with <code>CELERY__</code> is matched to a Celery setting as long as it exists. For example, the <code>CELERY__timezone</code> env var sets Celery's <code>timezone</code>, the <code>CELERY__worker_pool</code> env var sets Celery's <code>worker_pool</code>. And <code>CELERY__nonsense</code> is ignored because there is no <code>nonsense</code> setting in Celery.</p>
<pre><code class="lang-python"><span class="hljs-comment"># celeryconfig.py</span>
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> pydantic
<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> partial

settings = [
    (<span class="hljs-string">"accept_content"</span>, json.loads),
    (<span class="hljs-string">"enable_utc"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"imports"</span>, json.loads),
    (<span class="hljs-string">"include"</span>, json.loads),
    (<span class="hljs-string">"timezone"</span>, str),
    (<span class="hljs-string">"beat_max_loop_interval"</span>, int),
    (<span class="hljs-string">"beat_schedule"</span>, json.loads),
    (<span class="hljs-string">"beat_scheduler"</span>, str),
    (<span class="hljs-string">"beat_schedule_filename"</span>, str),
    (<span class="hljs-string">"beat_sync_every"</span>, int),
    (<span class="hljs-string">"broker_url"</span>, str),
    (<span class="hljs-string">"broker_transport"</span>, str),
    (<span class="hljs-string">"broker_transport_options"</span>, json.loads),
    (<span class="hljs-string">"broker_connection_timeout"</span>, int),
    (<span class="hljs-string">"broker_connection_retry"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"broker_connection_max_retries"</span>, int),
    (<span class="hljs-string">"broker_failover_strategy"</span>, str),
    (<span class="hljs-string">"broker_heartbeat"</span>, float),
    (<span class="hljs-string">"broker_login_method"</span>, str),
    (<span class="hljs-string">"broker_pool_limit"</span>, int),
    (<span class="hljs-string">"broker_use_ssl"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"cache_backend"</span>, str),
    (<span class="hljs-string">"cache_backend_options"</span>, json.loads),
    (<span class="hljs-string">"cassandra_table"</span>, str),
    (<span class="hljs-string">"cassandra_entry_ttl"</span>, int),
    (<span class="hljs-string">"cassandra_keyspace"</span>, str),
    (<span class="hljs-string">"cassandra_port"</span>, int),
    (<span class="hljs-string">"cassandra_read_consistency"</span>, str),
    (<span class="hljs-string">"cassandra_servers"</span>, json.loads),
    (<span class="hljs-string">"cassandra_write_consistency"</span>, str),
    (<span class="hljs-string">"cassandra_options"</span>, json.loads),
    (<span class="hljs-string">"s3_access_key_id"</span>, str),
    (<span class="hljs-string">"s3_secret_access_key"</span>, str),
    (<span class="hljs-string">"s3_bucket"</span>, str),
    (<span class="hljs-string">"s3_base_path"</span>, str),
    (<span class="hljs-string">"s3_endpoint_url"</span>, str),
    (<span class="hljs-string">"s3_region"</span>, str),
    (<span class="hljs-string">"couchbase_backend_settings"</span>, json.loads),
    (<span class="hljs-string">"arangodb_backend_settings"</span>, json.loads),
    (<span class="hljs-string">"mongodb_backend_settings"</span>, json.loads),
    (<span class="hljs-string">"event_queue_expires"</span>, float),
    (<span class="hljs-string">"event_queue_ttl"</span>, float),
    (<span class="hljs-string">"event_queue_prefix"</span>, str),
    (<span class="hljs-string">"event_serializer"</span>, str),
    (<span class="hljs-string">"redis_db"</span>, str),
    (<span class="hljs-string">"redis_host"</span>, str),
    (<span class="hljs-string">"redis_max_connections"</span>, int),
    (<span class="hljs-string">"redis_username"</span>, str),
    (<span class="hljs-string">"redis_password"</span>, str),
    (<span class="hljs-string">"redis_port"</span>, int),
    (<span class="hljs-string">"redis_backend_use_ssl"</span>, json.loads),
    (<span class="hljs-string">"result_backend"</span>, str),
    (<span class="hljs-string">"result_cache_max"</span>, int),
    (<span class="hljs-string">"result_compression"</span>, str),
    (<span class="hljs-string">"result_compression"</span>, str),
    (<span class="hljs-string">"result_exchange"</span>, str),
    (<span class="hljs-string">"result_exchange_type"</span>, str),
    (<span class="hljs-string">"result_expires"</span>, int),
    (<span class="hljs-string">"result_persistent"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"result_serializer"</span>, str),
    (<span class="hljs-string">"database_engine_options"</span>, json.loads),
    (<span class="hljs-string">"database_short_lived_sessions"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"database_db_names"</span>, json.loads),
    (<span class="hljs-string">"security_certificate"</span>, str),
    (<span class="hljs-string">"security_cert_store"</span>, str),
    (<span class="hljs-string">"security_key"</span>, str),
    (<span class="hljs-string">"task_acks_late"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_acks_on_failure_or_timeout"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_always_eager"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_annotations"</span>, json.loads),
    (<span class="hljs-string">"task_compression"</span>, str),
    (<span class="hljs-string">"task_create_missing_queues"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_default_delivery_mode"</span>, str),
    (<span class="hljs-string">"task_default_exchange"</span>, str),
    (<span class="hljs-string">"task_default_exchange_type"</span>, str),
    (<span class="hljs-string">"task_default_queue"</span>, str),
    (<span class="hljs-string">"task_default_rate_limit"</span>, int),
    (<span class="hljs-string">"task_default_routing_key"</span>, str),
    (<span class="hljs-string">"task_eager_propagates"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_ignore_result"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_publish_retry"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_publish_retry_policy"</span>, json.loads),
    (<span class="hljs-string">"task_queues"</span>, json.loads),
    (<span class="hljs-string">"task_routes"</span>, json.loads),
    (<span class="hljs-string">"task_send_sent_event"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_serializer"</span>, str),
    (<span class="hljs-string">"task_soft_time_limit"</span>, int),
    (<span class="hljs-string">"task_track_started"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_reject_on_worker_lost"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"task_time_limit"</span>, int),
    (<span class="hljs-string">"worker_agent"</span>, str),
    (<span class="hljs-string">"worker_autoscaler"</span>, str),
    (<span class="hljs-string">"worker_concurrency"</span>, int),
    (<span class="hljs-string">"worker_consumer"</span>, str),
    (<span class="hljs-string">"worker_direct"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_disable_rate_limits"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_enable_remote_control"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_log_color"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_log_format"</span>, str),
    (<span class="hljs-string">"worker_lost_wait"</span>, float),
    (<span class="hljs-string">"worker_max_tasks_per_child"</span>, int),
    (<span class="hljs-string">"worker_pool"</span>, str),
    (<span class="hljs-string">"worker_pool_putlocks"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_pool_restarts"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_prefetch_multiplier"</span>, int),
    (<span class="hljs-string">"worker_redirect_stdouts"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_redirect_stdouts_level"</span>, str),
    (<span class="hljs-string">"worker_send_task_events"</span>, partial(pydantic.parse_obj_as, bool)),
    (<span class="hljs-string">"worker_state_db"</span>, str),
    (<span class="hljs-string">"worker_task_log_format"</span>, str),
    (<span class="hljs-string">"worker_timer"</span>, str),
    (<span class="hljs-string">"worker_timer_precision"</span>, float)
]

<span class="hljs-keyword">for</span> setting, parse <span class="hljs-keyword">in</span> settings:
    env_var = <span class="hljs-string">f"CELERY__<span class="hljs-subst">{setting}</span>"</span>
    <span class="hljs-keyword">if</span> env_var <span class="hljs-keyword">in</span> os.environ:
        value = os.environ[env_var]
        value = parse(os.environ[env_var])
        globals()[setting] = value
</code></pre>
<p>I make use of some partial, pydantic and json jiggery pokery to do the parsing and type conversion. And that allows me to configure my Celery worker in a docker compose neatly:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">worker:</span>
  <span class="hljs-attr">image:</span> <span class="hljs-string">bstiel/celeryq:0.1</span>
  <span class="hljs-attr">restart:</span> <span class="hljs-string">always</span>
  <span class="hljs-attr">command:</span> [<span class="hljs-string">"celery"</span>, <span class="hljs-string">"--app=worker.app"</span>, <span class="hljs-string">"worker"</span>]
  <span class="hljs-attr">environment:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">"CELERY__broker_url=redis://redis:6379/1"</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">'CELERY__accept_content=["yaml", "json"]'</span>
</code></pre>
<p>PS: Just as I was wrapping up this blog post, I came across a Celery GitHub issue:</p>
<p><a target="_blank" href="https://github.com/celery/celery/issues/4284?ref=celery-school.ghost.io#issuecomment-1231677885">I came here looking for the opposite: a way to configure Celery with env vars</a>.</p>
<p>I am considering submitting a pull request, what do you think?</p>
]]></content:encoded></item><item><title><![CDATA[Docker Health Check for Celery Workers]]></title><description><![CDATA[The Docker healthcheck directive instructs Docker to run a command to check if a container is still working as expected. This helps detect cases where the…]]></description><link>https://celery.school/docker-health-check-for-celery-workers</link><guid isPermaLink="true">https://celery.school/docker-health-check-for-celery-workers</guid><category><![CDATA[celery]]></category><category><![CDATA[Docker]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Fri, 10 Feb 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/jOqJbvo1P9g/upload/9d86efe766d26f0cc97672823a6dbe42.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Docker healthcheck directive instructs Docker to run a command to check if a container is still working as expected.</p>
<p>This helps detect cases where the container process is still running but unable to<br />operate as intended. For example, an unresponsive Celery worker node.</p>
<p>A Docker container with a healthcheck directive has its health status reported next to its normal Docker status.</p>
<pre><code class="lang-bash">$ docker compose ps

NAME                            ...     STATUS
healthcheck-celery-worker-1     ...     Up 3 minutes (healthy)
</code></pre>
<p>The healthcheck can also be used to trigger auto-healing actions, though this feature is only available in Docker swarm mode.</p>
<p>In this article, I will show you how to set up a healthcheck direcxtive for a dockerised Celery worker node. I will explain:</p>
<ul>
<li><p><a target="_blank" href="https://celery-school.ghost.io/docker-healthcheck-for-celery-workers/#monitoring-a-celery-worker">how to monitor the health status of a Celery worker</a></p>
</li>
<li><p><a target="_blank" href="https://celery-school.ghost.io/docker-healthcheck-for-celery-workers/#docker-healthcheck">what you need to know about Docker HEALTHCHECK instruction</a></p>
</li>
<li><p><a target="_blank" href="https://celery-school.ghost.io/docker-healthcheck-for-celery-workers/#docker-healthcheck-for-celery-workers">a few gotchas when setting up the HEALTHCHECK for the Celery worker</a></p>
</li>
</ul>
<h2 id="heading-monitoring-a-celery-worker"><strong>Monitoring a Celery worker</strong></h2>
<p>Celery provides several commands to inspect and manage Celery worker nodes. I frequently use the <code>celery inspect ping</code> command to broadcast a ping to all registered Celery workers:</p>
<pre><code class="lang-bash">$ celery inspect ping
-&gt;  celery@ec531987a721: OK
        pong
-&gt;  celery@2a2078c9ffef: OK
        pong
-&gt;  celery@30a5e769daf7: OK
        pong
-&gt;  celery@0ddd0198151c: OK
        pong

4 nodes online.
</code></pre>
<p>If the ping command does not receive a response in time, it raises an error: "Error: No nodes replied within time constraint". Using the the <code>--destination</code> option, you can ping a particular worker node:</p>
<pre><code class="lang-bash">$ celery inspect ping --destination celery@ec531987a721
-&gt;  celery@ec531987a721: OK
        pong

1 node online.
</code></pre>
<p>Note that the reason a node is unresponsive might be down to broker connectivity issues or the broker being down alltogether. You might want to choose a different approach instead of <code>celery inspect ping</code> if you have specific requirements.</p>
<h2 id="heading-docker-healthcheck"><strong>Docker healthcheck</strong></h2>
<p>The Docker healthcheck directive consists of a command that Docker runs periodically to determine the container's health. It also consists of a set of parameters that specify the frequency at which the command is run.</p>
<p>You can specify the healthcheck in the Dockerfile so it becomes baked into the image:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-keyword">HEALTHCHECK</span><span class="bash"> --interval=30s --timeout=30s --start-period=5s --retries=3 CMD [ <span class="hljs-string">"executable"</span> ]</span>
</code></pre>
<p>You can also specify it in the Docker compose Yaml:</p>
<pre><code class="lang-yaml">    <span class="hljs-attr">worker:</span>
        <span class="hljs-string">...</span>
        <span class="hljs-attr">healthcheck:</span>
          <span class="hljs-attr">test:</span> [<span class="hljs-string">"CMD"</span>, <span class="hljs-string">"executable"</span>]
          <span class="hljs-attr">interval:</span> <span class="hljs-string">30s</span>
          <span class="hljs-attr">timeout:</span> <span class="hljs-string">30s</span>
          <span class="hljs-attr">retries:</span> <span class="hljs-number">3</span>
          <span class="hljs-attr">start_period:</span> <span class="hljs-string">5s</span>
</code></pre>
<p>With the parameters above, a fresh container defaults to "starting". After the initial start period (5 seconds), and every interval seconds (30 seconds), Docker runs "executable".</p>
<p>When the check passes (zero exit status), the container becomes "healthy". After a certain number (3 retries) of consecutive failures (non-zero exit status), it becomes "unhealthy".</p>
<h2 id="heading-docker-healthcheck-for-celery-workers"><strong>Docker healthcheck for Celery workers</strong></h2>
<p>By now you know how to ping a particular Celery worker node to determine whether it is responsive (healthy). You also know how to set up a Docker healtcheck command.</p>
<p>What is left to do is dockerise the Celery worker and implement the <code>celery inspect ping</code> command as the Docker healthcheck directive.</p>
<p>I have created a <a target="_blank" href="https://github.com/bstiel/docker-healthcheck-celery-worker?ref=celery-school.ghost.io">Github repository</a>. It consists of a Celery worker (<a target="_blank" href="https://celery-school.ghost.io/docker-healthcheck-for-celery-workers/#monitoring-a-celery-worker"><code>worker.py</code></a>) with one registered task (<code>do_something</code>) and a producer script (<a target="_blank" href="https://celery-school.ghost.io/docker-healthcheck-for-celery-workers/#monitoring-a-celery-worker"><code>producer.py</code></a>) that continuously invokes <code>do_something</code> via Celery.</p>
<p>The complete stack is defined in docker-compose.yml and includes Redis as a message broker. The Dockerfile contains the build instructions for the Celery worker node.</p>
<pre><code class="lang-plaintext">FROM python:3.11.1WORKDIR /appCOPY requirements.txt /app/requirements.txtRUN pip install -r requirements.txtCMD ["celery", "--app", "worker.app", "worker"]HEALTHCHECK --interval=10s --timeout=10s --start-period=3s --retries=3 CMD ["/sh", "-c", "celery inspect ping --destination celery@$HOSTNAME"]
</code></pre>
<p><a target="_blank" href="https://raw.githubusercontent.com/bstiel/docker-healthcheck-celery-worker/main/Dockerfile"><strong>view raw</strong></a><a target="_blank" href="https://github.com/bstiel/docker-healthcheck-celery-worker/blob/main/Dockerfile"><strong>Dockerfile</strong></a> delivered with ❤ by <a target="_blank" href="https://emgithub.com/"><strong>emgithub</strong></a></p>
<p>This CMD spins up the Celery worker node inside the container. The node registers itself under the name <code>celery@$HOSTNAME</code>. <code>$HOSTNAME</code> refers to the container's hostname which is usually the container's Docker ID - for example <code>f9207bc94b22</code>, unless you specify otherwise.</p>
<p>To make the HEALTHCHECK CMD</p>
<pre><code class="lang-bash">$ celery inspect ping --destination celery@<span class="hljs-variable">$HOSTNAME</span>
</code></pre>
<p>generic with respect to <code>$HOSTNAME</code>, you need Docker to resolve <code>$HOSTNAME</code> at runtime.</p>
<p>To support variable substitution, the shell format is required for the HEALTHCHECK CMD:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-keyword">HEALTHCHECK</span><span class="bash"> --interval=10s --timeout=10s --start-period=3s --retries=3 CMD celery inspect ping --destination celery@<span class="hljs-variable">$HOSTNAME</span></span>
</code></pre>
<p>Note the lack of any single or double quotes around the CMD in the shell format. You can also use the exec format and execute a shell directly:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-keyword">HEALTHCHECK</span><span class="bash"> --interval=10s --timeout=10s --start-period=3s --retries=3 CMD [<span class="hljs-string">"/sh"</span>, <span class="hljs-string">"-c"</span>, <span class="hljs-string">"celery inspect ping --destination celery@<span class="hljs-variable">$HOSTNAME</span>"</span>]</span>
</code></pre>
<p>When you spin up the container, docker will default to the "Starting" state for 3 seconds. After 3 seconds it will ping the container's Celery worker every 10 seconds. If the ping passes, the container becomes healthy. If the ping fails after 3 retries, the container becomes unhealthy.</p>
<p>You can also define the healthcheck in the Docker compose file. A Docker compose healthcheck property overrides any healthcheck directive defined in a Docker image:</p>
<pre><code class="lang-Yaml"><span class="hljs-attr">healthcheck:</span>
    <span class="hljs-attr">test:</span> [<span class="hljs-string">"CMD-SHELL"</span>, <span class="hljs-string">"celery inspect ping --destination celery@$$HOSTNAME"</span>]
    <span class="hljs-attr">interval:</span> <span class="hljs-string">30s</span>
    <span class="hljs-attr">timeout:</span> <span class="hljs-string">10s</span>
    <span class="hljs-attr">retries:</span> <span class="hljs-number">3</span>
    <span class="hljs-attr">start_period:</span> <span class="hljs-string">5s</span>
</code></pre>
<p>Note the <code>$$</code> for correctly escaping the environment variable. To disable a healthcheck directive alltogether, use:</p>
<pre><code class="lang-Yaml"><span class="hljs-attr">healthcheck:</span>
    <span class="hljs-attr">test:</span> [<span class="hljs-string">"NONE"</span>]
</code></pre>
<p>Or, if you want to disable any baseimage's healthcheck directive:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-keyword">HEALTHCHECK</span><span class="bash"> NONE</span>
</code></pre>
<p>Play around with the example repository. Bring up the <a target="_blank" href="https://github.com/bstiel/docker-healthcheck-celery-worker?ref=celery-school.ghost.io">Git repository's</a> Docker compose stack and check the celery-worker's health status with <code>docker compose ps</code>.</p>
<p>Remove the Redis broker <code>docker rm -f healthcheck-celery-broker-1</code> to simulate the Celery worker node becoming unresponsive. Wait for the health state to change. Bring the Redis container back up again and observe how the Celery worker's status responds.</p>
<p>Scale the number of workers up with <code>docker compose up -d --scale celery-worker=2</code> and check the health status in the additional worker.</p>
<p>Finally, to inspect and debug the healthcheck's output:</p>
<pre><code class="lang-bash">$ docker inspect --format <span class="hljs-string">"{{json .State.Health }}"</span> healthcheck-celery-worker-1
</code></pre>
<p>In a future blog post, I will expand on the healthcheck topic and explore how they can be used for auto-healing in Docker swarm mode and kubernetes.</p>
<p>Happy Celery coding!</p>
]]></content:encoded></item><item><title><![CDATA[Celery Dev Tip: Auto-reload Celery on Code Changes]]></title><description><![CDATA[For a long time, my most frustrating developer experience with Celery was the lack of worker restart on code changes. For example, Gunicorn supports a…]]></description><link>https://celery.school/watchfiles-reload-celery-worker-code-changes</link><guid isPermaLink="true">https://celery.school/watchfiles-reload-celery-worker-code-changes</guid><category><![CDATA[celery]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Bjoern Stiel]]></dc:creator><pubDate>Tue, 23 Apr 2019 11:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/gTs2w7bu3Qo/upload/424834c1bfd70b5d9ebe3b53a163a957.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>For a long time, my most frustrating developer experience with Celery was the lack of worker restart on code changes. For example, <a target="_blank" href="http://docs.gunicorn.org/en/stable/settings.html?ref=celery-school.ghost.io#reload">Gunicorn</a> supports a <code>--reload</code> argument. This setting causes workers to be restarted whenever your application code changes. Which is almost indispensable even when you are a disciplined TDD disciple 😉.</p>
<p>Unfortunately, Celery does not support such a reload option. Celery once had an <code>--autoreload</code> option but it was deprecated<br />in version 3.1.0 or so - though the documents suggested otherwise for a long time. Which only added to the frustration and confusion.</p>
<p>As of any recent Celery version, we are on our own when we want to avoid manual worker restarts after code changes. In this article, I am showing you a simple workaround to get your Celery worker restarted on code changes. This will simplify your Celery development workflow and<br />save you many <code>Ctrl+C</code>-<code>Arrow-Up</code>-<code>Enter</code> round trips.</p>
<h2 id="heading-watchdog-and-watchmedo"><strong>watchdog and watchmedo</strong></h2>
<p><a target="_blank" href="https://github.com/gorakhargosh/watchdog?ref=celery-school.ghost.io">watchdog</a> is a Python library to monitor file system events. When you create, edit, change or delete a file or a directory, watchdog raises an event that you can catch and handle. It runs on all big operating systems, including Linux, Max OS and Windows and works on Python 2.7 and 3.4+.</p>
<p>In addition to the actual Python API, watchdog comes with a utility script called <code>watchmedo</code>. We can run <code>watchmedo</code> on the command line to monitor a folder for file events. Whenever an event is raised, <code>watchmedo</code> restarts another command. Which is precisely what we are after in order to restart our Celery worker on code (Python file) changes. Install the watchdog package via <code>pip install watchdog</code> and that the <code>watchmedo</code> utility script works.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># install watchdog</span>
$ pip install watchdog
...

<span class="hljs-comment"># confirm watchmedo is installed</span>
$ watchmedo --<span class="hljs-built_in">help</span>
...
</code></pre>
<h2 id="heading-auto-restart-celery"><strong>Auto-restart Celery</strong></h2>
<p><code>watchmedo</code> supports an <code>auto-restart</code> argument. With this, it takes control of a long-running subprocess and restarts it on matched file system events. Have a look at <code>watchmedo auto-restart --help</code> for more details. Let's have a look at how we can use <code>watchmedo</code> to restart a celery worker whenever we modify our source code. Usually, I declare my Celery worker as <code>app</code> in a dedicated <a target="_blank" href="http://docs.gunicorn.org/en/stable/settings.html?ref=celery-school.ghost.io#reload"><code>worker.py</code></a> module and start the Celery worker with the <code>celery worker</code> command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker</span>
$ celery worker --app=worker.app --concurrency=1 --loglevel=INFO
</code></pre>
<p>Let's change that now and hand control over to <code>watchmedo</code>. We want <code>watchmedo</code> to restart the <code>celery worker</code> command on code-changes.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start celery worker indirectly via watchmedo</span>
$ watchmedo auto-restart --directory=./ --pattern=*.py --recursive -- celery worker --app=worker.app --concurrency=1 --loglevel=INFO
</code></pre>
<p>We tell <code>watchmedo</code> to monitor the current directory (<code>--directory=./</code>) and its all subdirectories (<code>--recursive</code>) for changes in any of the Python source files (<code>--pattern=*.py</code>). Whenever that happens, it kills the current celery worker (<code>auto-restart</code>) and spins up a new one (<code>celery worker --app=</code><a target="_blank" href="http://docs.gunicorn.org/en/stable/settings.html?ref=celery-school.ghost.io#reload"><code>worker.app</code></a> <code>--concurrency=1 --loglevel=INFO</code>). Note <code>--</code> before the command argument. This tells <code>watchmedo</code> to not interpret the Celery arguments.</p>
<p>Happy Celery coding!</p>
]]></content:encoded></item></channel></rss>