<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexander Godwin on Medium]]></title>
        <description><![CDATA[Stories by Alexander Godwin on Medium]]></description>
        <link>https://medium.com/@alecgee73?source=rss-823b77f2e9c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oxbEXLK0fOunQv7uynS-lA.jpeg</url>
            <title>Stories by Alexander Godwin on Medium</title>
            <link>https://medium.com/@alecgee73?source=rss-823b77f2e9c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:39:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alecgee73/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exploring Retrieval-Based Memory for AI Coding Agents]]></title>
            <link>https://medium.com/@alecgee73/exploring-retrieval-based-memory-for-ai-coding-agents-41d7ef237311?source=rss-823b77f2e9c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d7ef237311</guid>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Alexander Godwin]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 14:58:38 GMT</pubDate>
            <atom:updated>2025-11-24T14:58:38.073Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>What I’m about to write here is a battle of sorts between me and my thoughts. I need clarity on why these might or might not work, what the limitations are, as I’m currently trying to explore what&#39;s possible. I’m no expert in the subject matter; rather, I’m just looking for answers.</blockquote><p>Thinking back to the middle of this year (2025), when I was trying to build an ML model to achieve a certain “somewhat complex task” with the assistance of Claude code, just a side project. I ran into context summarization for the first time (I was confused and had to Google what it was). Needless to say, this context summarization (compaction) continued throughout the duration of the project, and the agent kept forgetting what it had done before the context summarization occurred.</p><p>While searching for solutions, I came across a suggestion stating that it’s best to instruct the agent to create a “summary.md” file, where it will write the entire summary of the codebase and what had been done previously. Whenever the context is compacted, or the agent restarts, it would simply look into the summary.md to get up to date.</p><p>This did not solve the context issues; it wasn’t even intended to. I eventually left the project to work on another idea. I think I could blame myself partially, because I’m not an ML engineer, I saw coding agents and thought of all the possibilities I could achieve with it…</p><p>I recently began exploring Retrieval Augmented Generation Systems (RAGS) again, following my initial foray in mid-2024. With the inception of agentic RAGS, using tool calls and all, such systems are now very powerful.</p><p>So I’ve been thinking, what if there’s a way to use Agentic RAGS and vector databases as a brain for coding agents? What could be the limitations of such a system? Is it even feasible?</p><p>Let me break down what I’m thinking. If it is possible to dynamically build up the context for each prompt or task, that might just be one solution to the context window problem. Could we chunk up the context memory and store it in a vector database for retrieval when needed?</p><pre>human: Can you do ***<br><strong>agent: Making a plan to achieve ***</strong><br>  tool call: retrieve relevant context for achieving *** based on plan<br><strong>agent: Using the context that has been built up dynamically, execute the task</strong></pre><p>This is just a conceptual explanation of what I&#39;m thinking. If this works, then it could potentially allow conversations to be continuous while the context window itself is kept optimal. With this, the user might not have to edit the context themselves, because it would be intelligently handled by the agent.</p><p>I know that currently, it’s probably best that you use an agent instance or process to achieve one task at a time, but I think this is just because of the limited context window issue, to avoid context summarization and compaction.</p><p>The core idea of this article is this:</p><pre>Instead of summarizing or dumping:<br>- Store all context in vector databases<br>- Retrieve only relevant context per turn<br>- Never lose detail, never hit limits</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMrF9vEpbY1MxJsraeTCHA.png" /><figcaption>Overall system architecture</figcaption></figure><p><strong>Key Thought</strong>: If retrieval precision is high enough (&gt;90%), <br>This should work better than summarization.</p><p>What I’m exploring is how to model long-term and working memory for AI coding agents in the same way humans have.</p><p>I’m curious to know from engineers more experienced than I:</p><ol><li>Why might this approach not work?</li><li>What are the failure modes? When would retrieval miss crucial context? How to handle context invalidation?</li><li>Has this been tried and failed? What did I miss in my analysis? What makes this harder than it seems?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d7ef237311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling websockets in TaskForge]]></title>
            <link>https://medium.com/@alecgee73/scaling-websockets-in-taskforge-7e852d48b186?source=rss-823b77f2e9c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e852d48b186</guid>
            <category><![CDATA[websocket-server]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Alexander Godwin]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 20:37:10 GMT</pubDate>
            <atom:updated>2025-10-21T20:37:10.686Z</atom:updated>
            <content:encoded><![CDATA[<p>Websockets enable bi-directional communication between clients and servers. Unlike the traditional HTTP requests, which are stateless for the most part, websockets have some sort of state, since connections are opened and live for a period of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cb-3-In-sD-utzBnfahCTQ.png" /></figure><blockquote>The fact that these connections are long-lived and have states poses a couple of issues when trying to scale websockets. These problems come up in terms of hardware resources, such as memory and CPU.</blockquote><p>There’s only so much memory and CPU that a server can have; at some point in time, the load (open connections) on the server will result in lags and improperly closed connections.</p><p>Since websockets are bi-directional in nature, once a connection is open, the server holds a reference to the socket, and the client should always connect to that same instance of the websocket server if it is available, to reduce the latency of always re-establishing a connection.</p><p>Now that websockets are clear, the remainder of this post will show how I solved the problem with scaling WebSocket connections in TaskForge.</p><h4>How TaskForge makes use of WebSockets</h4><p>In Taskforge, I used websockets to carry out real-time status updates of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FA1_VZWUJ_jE93Lz7EnugA.png" /><figcaption>High level overview of how Taskforge uses websockets</figcaption></figure><p>Clients authenticate with the gateway-node service, the current session is cached in Redis, and then the tokens are returned to the client. Finally, the client uses the access token to authenticate with the WebSocket server, then validates the token by Redis for the associated user session.</p><p>When the client creates a task, the gateway-node service returns an ID that the client can use to subscribe to updates on the WebSocket server.</p><p>Following that, the problem I have to solve becomes clear</p><ol><li>Taskforge is deployed with a Horizontal Pod Autoscaler (HPA) on EKS, which means we will have multiple instances of the WS server at some point or the other.</li><li>Always guarantee that the server with the appropriate connection publishes responses to the client.</li></ol><p>Starting from problem 1, if solved properly, it will provide the basics for the solution to problem 2.</p><p>The first step is to determine how to maintain accurate tracking of the connection (user/socketId) &amp; subscription (userId/taskId) pairings, preferably outside of any instance of the status-gateway service. I chose Redis for this purpose, seeing as it’s already used for caching user sessions.</p><pre>import Redis from &quot;ioredis&quot;<br>import dotenv from &quot;dotenv&quot;<br>import { TaskStatusUpdate } from &quot;../types&quot;<br><br>dotenv.config()<br>const redis = new Redis(process.env.REDIS_URL!)<br><br>const STATUS_TTL = 60 * 60 // 1 hour<br><br>export class TaskStatusCache {<br>  async setStatus(taskId: string, status: TaskStatusUpdate): Promise&lt;void&gt; {<br>    await redis.set(<br>      `task:${taskId}:last-status`,<br>      JSON.stringify(status),<br>      &quot;EX&quot;,<br>      STATUS_TTL<br>    )<br>  }<br><br>  async getStatus(taskId: string): Promise&lt;TaskStatusUpdate | null&gt; {<br>    const json = await redis.get(`task:${taskId}:last-status`)<br>    return json ? JSON.parse(json) : null<br>  }<br><br>  async clearStatus(taskId: string): Promise&lt;void&gt; {<br>    await redis.del(`task:${taskId}:last-status`)<br>  }<br>}</pre><p>This is the logic for getting &amp; setting task status in Redis.</p><pre>import Redis from &quot;ioredis&quot;<br>import dotenv from &quot;dotenv&quot;<br><br>dotenv.config()<br>const redis = new Redis(process.env.REDIS_URL!)<br><br>export class SubscriptionService {<br>  private prefix = &quot;task&quot;<br><br>  async addSubscriber(taskId: string, userId: string): Promise&lt;void&gt; {<br>    await redis.sadd(`${this.prefix}:${taskId}:subscribers`, userId)<br>  }<br><br> <br>  async removeSubscriber(taskId: string, userId: string): Promise&lt;void&gt; {<br>    await redis.srem(`${this.prefix}:${taskId}:subscribers`, userId)<br>  }<br><br>  <br>  async getSubscribers(taskId: string): Promise&lt;string[]&gt; {<br>    return await redis.smembers(`${this.prefix}:${taskId}:subscribers`)<br>  }<br><br>  <br>  async clearTask(taskId: string): Promise&lt;void&gt; {<br>    await redis.del(`${this.prefix}:${taskId}:subscribers`)<br>  }<br><br>  async getUserTasks(userId: string): Promise&lt;string[]&gt; {<br>    const keys = await redis.keys(`${this.prefix}:*:subscribers`)<br>    const matchingTasks: string[] = []<br><br>    for (const key of keys) {<br>      const isMember = await redis.sismember(key, userId)<br>      if (isMember) {<br>        const [, taskId] = key.split(&quot;:&quot;)<br>        matchingTasks.push(taskId)<br>      }<br>    }<br><br>    return matchingTasks<br>  }<br>}</pre><p>We keep track of user subscriptions to tasks using the logic above.</p><p>Then, we have the Redis subscription logic as follows:</p><pre>import { TaskStatusUpdate } from &quot;./types&quot;<br>import { broadcastToTask } from &quot;./socket.server&quot;<br>import dotenv from &quot;dotenv&quot;<br>import { withLogContext } from &quot;./lib/log-context&quot;<br>import { statusUpdateCounter } from &quot;./lib/metrics&quot;<br>import {<br>  createResilientRedis,<br>  isRedisHealthy,<br>  redisCircuitBreaker,<br>} from &quot;./lib/redis-resilience&quot;<br><br>dotenv.config()<br><br>const log = withLogContext({ service: &quot;status-gateway&quot; })<br>let isSubscribed = false<br>const pattern = &quot;task:*:status&quot;<br><br>const redis = createResilientRedis(process.env.REDIS_URL!, async () =&gt; {<br>  if (!isSubscribed || !isAlreadySubscribed(pattern)) {<br>    log.info(&quot;Resubscribing after reconnection&quot;)<br>    await subscribeToTaskStatus()<br>  } else {<br>    log.info(&quot;Already subscribed to Redis, skipping resubscription&quot;)<br>  }<br>})<br><br>const isAlreadySubscribed = (pattern: string): boolean =&gt; {<br>  return (redis as any).subscriptionSet?.has(pattern) || false<br>}<br><br>export const subscribeToTaskStatus = async () =&gt; {<br>  // Check if already subscribed to prevent duplicate subscriptions<br>  if (isSubscribed &amp;&amp; isAlreadySubscribed(pattern)) {<br>    log.info(&quot;Already subscribed to Redis, skipping&quot;)<br>    return<br>  }<br><br>  try {<br>    await redisCircuitBreaker.execute(async () =&gt; {<br>      const result = await redis.psubscribe(pattern)<br>      isSubscribed = true<br>      log.info(&quot;Subscribed to task:*:status&quot;)<br>      return result<br>    })<br>  } catch (err) {<br>    log.error({ err }, &quot;Failed to subscribe to Redis&quot;)<br>  }<br>}<br><br>redis.on(&quot;pmessage&quot;, async (_, channel, message) =&gt; {<br>  try {<br>    await redisCircuitBreaker.execute(async () =&gt; {<br>      statusUpdateCounter.inc()<br>      const [, taskId] = channel.split(&quot;:&quot;)<br>      const context = log.child({ taskId })<br>      const update: TaskStatusUpdate = JSON.parse(message)<br>      context.info(`Task:${taskId} status updated to ${update.status}`)<br>      await broadcastToTask(taskId, update)<br>    })<br>  } catch (error) {<br>    log.error(<br>      { error: error instanceof Error ? error.message : &quot;Unknown error&quot; },<br>      &quot;Error processing Redis message&quot;<br>    )<br>  }<br>})<br><br>redis.on(&quot;close&quot;, () =&gt; {<br>  isSubscribed = false<br>  log.warn(&quot;Redis connection closed, subscription lost&quot;)<br>})<br><br>export { redis, isRedisHealthy }</pre><p>We’re subscribing to the pattern task:*:status, where “*” is a wildcard for task IDs. There are some other things, like redisCircuitBreaker; we’ll discuss circuit breakers and how they are used in Tasforge in-depth in a different post.</p><p>Finally, here’s the WebSocket server:</p><pre>import { WebSocketServer, WebSocket } from &quot;ws&quot;<br>import { verifyToken } from &quot;./auth&quot;<br>import { SubscriptionService } from &quot;./services/subscription.service&quot;<br>import { ConnectionStore } from &quot;./services/connection.store&quot;<br>import { ClientMessage, TaskStatusUpdate } from &quot;./types&quot;<br>import { v4 as uuidv4 } from &quot;uuid&quot;<br>import { TaskStatusCache } from &quot;./services/task-status.cache&quot;<br>import { withLogContext } from &quot;./lib/log-context&quot;<br>import { clientConnectionsCounter, activeClientsGauge } from &quot;./lib/metrics&quot;<br><br>const statusCache = new TaskStatusCache()<br>const subscriptionService = new SubscriptionService()<br>const connectionStore = new ConnectionStore()<br><br>export const sockets = new Map&lt;string, WebSocket&gt;() // socketId → socket<br><br>const HEARTBEAT_INTERVAL = 30000<br><br>type User = {<br>  email: string<br>  id: string<br>}<br><br>const log = withLogContext({ service: &quot;status-gateway&quot; })<br><br>export const initWebSocket = (serverPort: number) =&gt; {<br>  const wss = new WebSocketServer({ port: serverPort })<br>  log.info(`📡 WebSocket server listening on port ${serverPort}`)<br><br>  wss.on(&quot;connection&quot;, async (ws, req) =&gt; {<br>    clientConnectionsCounter.inc()<br>    activeClientsGauge.inc()<br>    const url = new URL(req.url || &quot;&quot;, `http://${req.headers.host}`)<br>    const token = url.searchParams.get(&quot;token&quot;)<br>    const socketId = uuidv4()<br><br>    // is alive<br>    ;(ws as any).isAlive = true<br><br>    ws.on(&quot;pong&quot;, () =&gt; {<br>      ;(ws as any).isAlive = true<br>    })<br><br>    try {<br>      const user: User = await verifyToken(token || &quot;&quot;)<br>      const userId = user.id<br><br>      // Save socket reference<br>      sockets.set(socketId, ws)<br><br>      // Register in Redis<br>      await connectionStore.registerConnection(userId, socketId)<br>      log.info(`Client connected: ${user.email} [${socketId}]`)<br><br>      // Handle incoming messages<br>      ws.on(&quot;message&quot;, async (raw) =&gt; {<br>        log.info(JSON.parse(raw.toString()))<br>        try {<br>          const msg = JSON.parse(raw.toString()) as ClientMessage<br>          if (msg.type === &quot;subscribe&quot; &amp;&amp; msg.taskId) {<br>            await subscriptionService.addSubscriber(msg.taskId, userId)<br><br>            // Immediately respond with current status (if exists)<br>            const cached = await statusCache.getStatus(msg.taskId)<br>            if (cached) {<br>              ws.send(JSON.stringify({ taskId: msg.taskId, ...cached }))<br>            }<br><br>            log.info(`${user.email} subscribed to ${msg.taskId}`)<br>          }<br>        } catch {<br>          log.warn(&quot;Invalid message&quot;)<br>        }<br>      })<br><br>      // Cleanup on disconnect<br>      ws.on(&quot;close&quot;, async () =&gt; {<br>        activeClientsGauge.dec()<br>        log.info(`Disconnected: ${user.email} [${socketId}]`)<br>        sockets.delete(socketId)<br>        await connectionStore.removeConnection(socketId)<br><br>        // clean all subscriptions<br>        const taskIds = await subscriptionService.getUserTasks(userId)<br>        for (const taskId of taskIds) {<br>          await subscriptionService.removeSubscriber(taskId, userId)<br>        }<br>      })<br>    } catch (err: any) {<br>      console.log(err)<br>      log.error(&quot;Invalid token:&quot;, err.message)<br>      ws.close()<br>    }<br>  })<br><br>  setInterval(async () =&gt; {<br>    for (const [socketId, ws] of sockets.entries()) {<br>      const alive = (ws as any).isAlive<br><br>      if (!alive) {<br>        console.log(`Socket ${socketId} unresponsive. Terminating...`)<br>        ws.terminate()<br>        sockets.delete(socketId)<br>        await connectionStore.removeConnection(socketId)<br>        continue<br>      }<br><br>      (ws as any).isAlive = false<br>      ws.ping()<br>    }<br>  }, HEARTBEAT_INTERVAL)<br>}</pre><p>A couple of interesting things are going on in the WebSocket server above. Let’s walk through the implementation:</p><p>The first thing we do whenever we have a new connection is to verify the authentication token. If the token is valid, we create a socket ID for the user and save the socket reference to a hash map in the server’s memory.</p><p>We have to store the socket reference in memory because</p><pre>const socketId = uuidv4()<br>...<br>sockets.set(socketId, ws)</pre><p>Next, we cache the userId along with the socketId in Redis for quick retrieval.</p><pre>await connectionStore.registerConnection(userId, socketId)</pre><p>In my opinion, this is a better approach than saving the userId-socketIdpairing in memory for a couple of reasons:</p><ol><li>This will eliminate the need to have a different service to check which server instance has a particular userId-socketId pairing. We’ll discuss more about this later.</li><li>Using Redis to cache the pairing allows us to free up the server’s memory.</li></ol><p>When we receive a message with the type of subscribe We also store taskId-userId pair in Redis.</p><pre>await subscriptionService.addSubscriber(msg.taskId, userId)</pre><p>Finally, when we receive a close event, we clean up the entire connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wT2XSr8qafVo9qFFnKfU4g.png" /><figcaption>general web socket flow</figcaption></figure><p>We’ve seen how connections &amp; subscriptions are carried from the client to the server, but that&#39;s only half of the entire flow. The second is how we publish messages that we receive from worker services to the clients.</p><p>The worker services periodically publish messages of task progress to the Redis channel. When such messages are published, our socket server picks them up, since it is subscribed to the pattern channel.</p><p>We extract the taskId then we invoke the braodcastToTask() function as follows:</p><pre>await broadcastToTask(taskId, update)</pre><p>Here’s the broadcastToTask() function:</p><pre>export const broadcastToTask = async (<br>  taskId: string,<br>  data: TaskStatusUpdate<br>) =&gt; {<br>  if ([&quot;completed&quot;, &quot;failed&quot;].includes(data.status)) {<br>    await statusCache.clearStatus(taskId)<br>  } else {<br>    await statusCache.setStatus(taskId, data)<br>  }<br><br>  const userIds = await subscriptionService.getSubscribers(taskId)<br><br>  for (const userId of userIds) {<br>    const socketIds = await connectionStore.getUserSocketIds(userId)<br>    for (const socketId of socketIds) {<br>      const socket = sockets.get(socketId)<br>      if (socket &amp;&amp; socket.readyState === WebSocket.OPEN) {<br>        socket.send(JSON.stringify({ taskId, ...data }))<br>      }<br>    }<br>  }<br>}</pre><p>All we are doing in this function is to get a list of userIds of all subscribers to a particular task, and then we can iterate through the list, fetch the socketId for each userId then we check which socketId this server instance manages, finally, we publish task updates to the client if its socket is still OPEN.</p><p>Notice that we have all server instances carry out this check. Even when we have multiple instances of the socket server, we are sure that a client will always receive the published message just once, because only the instance that has its socket reference will send the message to the client.</p><blockquote>This will eliminate the need to have a different service to check which server instance has a particular <em>userId-socketId</em> pairing. We’ll discuss more about this later.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjTxLLccZNGjoN1rI4VceQ.png" /><figcaption>status gateway service architecture</figcaption></figure><p>However, the major bottleneck I’ve noticed in this architecture is that when a server instance fails or restarts for whatever reason, the socket references in the server&#39;s memory are all lost, forcing clients to reconnect. It’s not a problem in Taskforge’s use case, but it is worth mentioning.</p><p>Thanks for reading, guys. See you all in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e852d48b186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring The Outbox Pattern For Taskforge]]></title>
            <link>https://medium.com/@alecgee73/exploring-the-outbox-pattern-for-taskforge-1dca53196d9e?source=rss-823b77f2e9c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dca53196d9e</guid>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Alexander Godwin]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 15:48:39 GMT</pubDate>
            <atom:updated>2025-10-13T15:48:39.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Challenges arise at every point when building a system like <a href="https://medium.com/@alecgee73/taskforge-a-distributed-task-processing-system-d67071710651">Taskforge</a>. One such challenge occurs around ensuring consistency between the data in the database and the data in RabbitMQ.</p><blockquote>How to achieve consistency between PostgreSQL and RabbitMQ</blockquote><p>Take, for example, a user submits a task to be processed. We want to ensure that this task is properly stored in the database and also sent to RabbitMQ for consumption by the worker services.</p><p>The first method we might think about is to create a database transaction to handle the insertion of the task into the database, and within that same transaction, publish the task to RabbitMQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fh40THNRC4_tc5B5rph6kg.png" /><figcaption>Basic publish</figcaption></figure><p>Let’s say in the transaction we:</p><ol><li>First, insert the task into the database, then</li><li>We publish the task to RabbitMQ</li></ol><p>Okay, this looks solid at first glance, given that the task is inserted into the database at first, if something happens at any point in the database insertion, transactions guarantee rollback, cool. But what if nothing happens during database insertion, rather, something goes wrong when publishing the task to RabbitMQ?</p><p>Maybe it’ll be better if we reverse the approach as follows:</p><ol><li>We first publish the task to RabbitMQ, then</li><li>We can safely insert the task into the database</li></ol><p>That way, RabbitMQ is always guaranteed to get the task first, before we insert it into the database. There, problem solved, right? right?… Not quite. We still face the same issues stated above.</p><p>We lose consistency easily if there’s a break in any part of this architecture, and it all stems from the confusion of how database transactions actually work versus what developers think transactions do.</p><blockquote>The main problem is that database transactions do not account for other operations that are not database-bound (e.g, external API calls, writing to queues, etc). It’s not a problem, it’s just how it is… When you think about it the database actually has no business with your other infrastructure.</blockquote><p>If only database transactions could account for other types of operations. Well, unfortunately, they don’t, but there’s a pattern that comes in handy in such cases.</p><h3><strong>Outbox Pattern</strong></h3><p>The outbox pattern is an architectural paradigm, where rather than using a single database transaction to perform the insert and publish operations, and hope that nothing breaks, we instead use the transaction to insert the task into the database when the create task endpoint is hit.</p><blockquote>Okay, you have to be kidding me. How does RabbitMQ get the data? Isn’t the entire point to have the data in both the database and RabbitMQ?</blockquote><p>Exactly, we want to achieve a level of consistency, but no one said it has to happen immediately. We could aim for <strong>eventual consistency</strong> instead, which means that the database and RabbitMQ would eventually be in sync, usually in a matter of seconds.</p><p>To achieve this <strong>eventual consistency</strong>, we create a separate service called the outbox-publisher. Its job is to poll the database at certain intervals to get pending tasks, then publish these tasks to RabbitMQ, and finally update the status of the tasks to “dispatched”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OufoeiSJErY2Dg0YQOhC-w.png" /><figcaption>Outbox pattern</figcaption></figure><p>We can see that if there’s a problem with RabbitMQ, the outbox publisher could easily throw an error and never update the status of the tasks. This repeats until the publisher can successfully re-establish a connection with RabbitMQ, or whatever the issue was is fixed.</p><pre>export async function publishOutbox(type: string) {<br>  const end = taskDuration.startTimer()<br>  const pending = await db<br>    .table(&quot;Outbox&quot;)<br>    .where(&quot;status&quot;, &quot;pending&quot;)<br>    .where({ eventType: type })<br>    .limit(20)<br>    .orderBy(&quot;createdAt&quot;, &quot;asc&quot;)<br><br>  for (const entry of pending) {<br>    const routingKey = entry.eventType<br>    const context = log.child({ taskId: entry.taskId, traceId: entry.traceId })<br><br>    context.info(`Publishing ${entry.taskId}`)<br>    try {<br>      await publishToQueue(routingKey, entry.payload)<br><br>      await db.table(&quot;Outbox&quot;).where(&quot;id&quot;, entry.id).update({<br>        status: &quot;dispatched&quot;,<br>        dispatchedAt: new Date(),<br>      })<br><br>      taskCounter.labels(routingKey).inc()<br>      context.info(`Dispatched task ${entry.taskId}`)<br>    } catch (err) {<br>      taskErrorCounter.inc()<br>      context.error({ err }, `Failed to publish ${entry.id}`)<br>    } finally {<br>      end()<br>    }<br>  }<br>}</pre><p>In the implementation above, “Outbox” is a table where tasks ready for publishing are stored. So we have two tables, “Task” and “Outbox”, which are both written to in a transaction at task creation time. This is not necessary, as you could just set a field on the Task table to indicate the task publish status.</p><p>There’s also a feature called <a href="https://www.rabbitmq.com/docs/confirms#publisher-confirms"><strong>publisher confirms</strong></a> in RabbitMQ, which is similar to consumer acknowledgements, but it’s for publishers. I’m not making use of publisher confirms in Taskforge, as it’s overkill, but you are free to check it out.</p><p>The database is the single source of truth in this implementation of the outbox pattern, and the state of all other components will eventually be updated from the database.</p><h3><strong>Adaptive Outbox Publisher</strong></h3><p>Another interesting challenge that came up was how to ensure that the outbox-publisher can publish tasks adaptively to somewhat manage the back pressure from RabbitMQ.</p><p>For instance, Taskforge supports a couple of task types, like resize-image, compress-video, and generate-pdf. We could publish at similar rates, i.e, just fetch tasks from the database and publish to RabbitMQ irrespective of the task type. Seeing as we have no idea what service users will use most, at least at first, and different tasks have different CPU &amp; memory requirements, leading to different processing times, using a general publish rate for all task types would be tricky to scale.</p><blockquote>Publishing tasks at the same rate given all these variables is just not a scalable option as it may cause one or more queues to get overflow leading to backpressure and dropping of tasks. Meanwhile the other queues will continue to function properly.</blockquote><p>Taskforge has different queues for the different task types. With this feature in place, we can now consider how to make the outbox-publisher service adaptive.</p><pre>class SmartOutboxPublisher {<br>  publishInterval: number<br>  channel: Channel<br>  intervalNumber: any<br>  type: string<br><br>  constructor(type: string) {<br>    this.type = type<br>    this.publishInterval = 0<br>    this.channel = channel<br>  }<br><br>  public setChannel(channel: Channel) {<br>    this.channel = channel<br>    return this<br>  }<br><br>  async computeDynamicPublishingFrequency(routingKey: string) {<br>    const queues: Record&lt;string, string&gt; = {<br>      &quot;generate-pdf&quot;: &quot;task.generate-pdf&quot;,<br>      &quot;resize-image&quot;: &quot;task.resize-image&quot;,<br>      &quot;compress-video&quot;: &quot;task.compress-video&quot;,<br>    }<br><br>    try {<br>      const { messageCount, consumerCount } = await this.channel.checkQueue(<br>        queues[routingKey]<br>      )<br><br>      log.info(<br>        `Queue Stats: [messageCount - ${messageCount}, consumerCount - ${consumerCount}]`<br>      )<br><br>      const backlogPerConsumer =<br>        consumerCount &gt; 0 ? messageCount / consumerCount : messageCount<br><br>      let publishInterval = 5000<br><br>      if (backlogPerConsumer &gt; 100) {<br>        publishInterval = 15000<br>      } else if (backlogPerConsumer &gt; 50) {<br>        publishInterval = 10000<br>      } else {<br>        publishInterval = 5000<br>      }<br><br>      return publishInterval<br>    } catch (error) {<br>      log.error(<br>        {<br>          error: error instanceof Error ? error.message : &quot;Unknown error&quot;,<br>        },<br>        &quot;Invalid Queue - Queue doesn&#39;t exist&quot;<br>      )<br>      return -1<br>    }<br>  }<br><br>  async setUpInterval(<br>    routingKey: string,<br>    publishCallback: () =&gt; Promise&lt;void&gt;<br>  ) {<br>    const publishInterval = await this.computeDynamicPublishingFrequency(<br>      routingKey<br>    )<br><br>    if (this.publishInterval === publishInterval || publishInterval === -1) {<br>      return<br>    }<br><br>    this.cancelInterval()<br><br>    this.intervalNumber = setInterval(async () =&gt; {<br>      try {<br>        await publishCallback()<br>      } catch (error) {<br>        log.error(<br>          {<br>            error: error instanceof Error ? error.message : &quot;Unknown error&quot;,<br>          },<br>          `Error in ${this.type} publish loop`<br>        )<br>      }<br>    }, publishInterval)<br><br>    this.publishInterval = publishInterval<br>    log.info({<br>      message: `${routingKey} tasks currently publishing at ${<br>        publishInterval / 1000<br>      } secs`,<br>    })<br>  }<br><br>  cancelInterval() {<br>    clearInterval(this.intervalNumber)<br>  }<br>}<br><br>export const resizeImagePublisher = new SmartOutboxPublisher(&quot;resize-image&quot;)<br>export const compressVideoPublisher = new SmartOutboxPublisher(&quot;compress-video&quot;)<br>export const generatePdfPublisher = new SmartOutboxPublisher(&quot;generate-pdf&quot;)</pre><p>This is how an “adaptive” outbox-publisher might look; this is just my implementation. What I’m doing is setting the intervals at which the outbox-publisher service polls the “Outbox” table for the different types of tasks. By simply checking the consumer count and message count for a particular queue, we can set the polling intervals adaptively.</p><pre>const initializeServices = async () =&gt; {<br>  try {<br>    const channel = await connectToRabbitMQ()<br><br>    setInterval(async () =&gt; {<br>      try {<br>        await runServicePublishers(channel)<br>      } catch (error) {<br>        log.error(<br>          {<br>            error: error instanceof Error ? error.message : &quot;Unknown error&quot;,<br>          },<br>          &quot;Error in publish loop&quot;<br>        )<br>      }<br>    }, 60 * 1000)<br><br>    log.info(&quot;All services initialized successfully&quot;)<br>  } catch (error) {<br>    log.error(<br>      {<br>        error: error instanceof Error ? error.message : &quot;Unknown error&quot;,<br>      },<br>      &quot;Failed to initialize services&quot;<br>    )<br>    process.exit(1)<br>  }<br>}<br><br>const runServicePublishers = async (channel: any) =&gt; {<br>  await Promise.all([<br>    resizeImagePublisher<br>      .setChannel(channel)<br>      .setUpInterval(&quot;resize-image&quot;, () =&gt; publishOutbox(&quot;resize-image&quot;)),<br>    compressVideoPublisher<br>      .setChannel(channel)<br>      .setUpInterval(&quot;compress-video&quot;, () =&gt; publishOutbox(&quot;compress-video&quot;)),<br>    generatePdfPublisher<br>      .setChannel(channel)<br>      .setUpInterval(&quot;generate-pdf&quot;, () =&gt; publishOutbox(&quot;generate-pdf&quot;)),<br>  ])<br>}<br><br>initializeServices()</pre><p>This implementation shows how we’re using the adaptive publisher. A cycle is set for 60 seconds. This means that every 60 seconds, it re-evaluates the rate at which the database is polled for each task type. If there are no changes, we continue to publish at the same rate; otherwise, we publish at a new rate. A particular publishing rate for a task type will last an entire cycle, e.g, if the publishing rate for the resize-image service is currently 5 seconds, it’ll publish at that rate until the next cycle begins, publishing a total of (60 / 5 = 12) times during that cycle.</p><p><strong>Change Data Capture (CDC)</strong></p><p>This is a subjectively better alternative to the Outbox pattern. I say subjectively because it offers multiple advantages, but it’s complex to implement, and it might require an extra tool. It depends on the resources available to the team.</p><p>CDC can be implemented using <a href="https://www.postgresql.org/docs/current/wal-intro.html"><strong>WAL (write-ahead-log)</strong></a> streaming, but it’s usually time-consuming to an extent, so tools like <a href="https://debezium.io/documentation/reference/stable/connectors/postgresql.html"><strong>Debezium</strong></a> are readily available, and Debezium publishes every row-level change to Kafka. I think Prisma has a CDC feature too (Prisma Pulse), which works well with PostgreSQL.</p><blockquote>Implementing CDC using WAL streaming might be a fun side project for the near future, who knows? might not be all that fun… 😂</blockquote><p>Anyway, we’re at the end of this post, hopefully it’s a nice read, and it explains how I implemented the Outbox pattern in Taskforge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dca53196d9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taskforge: A Distributed Task Processing System]]></title>
            <link>https://medium.com/@alecgee73/taskforge-a-distributed-task-processing-system-d67071710651?source=rss-823b77f2e9c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d67071710651</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Alexander Godwin]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 20:16:01 GMT</pubDate>
            <atom:updated>2025-10-18T21:39:07.685Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A microservices-based distributed system showcasing modern architectural patterns for task processing, built with Node.js (TypeScript), featuring Go and Python workers, and containerized with Docker/Kubernetes.</blockquote><h3><strong>Why Build Taskforge?</strong></h3><p>I’ve always wanted to know how systems scale in production, and how big companies and experienced engineers handle systems at scale. Like every other engineer who has read system design books, blog posts, watched videos, and even listened to podcasts. I was curious about how to practically build a system that can scale.</p><p>As a software engineer, I’ve realized that I can’t afford to get lost in concepts &amp; big ideas, because we are builders, and without trying things out practically, how can I ever tell how &amp; why such a system works? The knowledge might as well just be stale. So I wanted to try my hand at building &amp; deploying such a system.</p><h3>Taskforge Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwIcc1PhdigLDAMR6-cqHA.png" /><figcaption>High level architechture of taskforge</figcaption></figure><p>The image above shows the high-level architecture of Taskforge. It shows the basic interaction between each of the services and the core infrastructure.</p><p><strong>Services</strong></p><ol><li><strong>gateway-node</strong>: Written in TypeScript for API Gateway &amp; Authentication</li><li><strong>status-gateway</strong>: Written in TypeScript, carries out WebSocket status updates</li><li><strong>outbox-publisher</strong>: A TypeScript service for Event publishing with the outbox pattern</li><li><strong>generate-pdf-worker</strong>: A Python PDF generation service</li><li><strong>resize-image: </strong>Go Image processing service</li><li><strong>compress-video</strong>: Python Video compression service</li><li><strong>chromium-renderer</strong>: TypeScript HTML to PDF rendering service</li></ol><p><strong>Infrastructure</strong></p><ol><li><strong>Database</strong>: PostgreSQL with Prisma (schema) + Knex (queries) hybrid approach</li><li><strong>Message Broker</strong>: RabbitMQ for async communication</li><li><strong>Cache</strong>: Redis for session management and caching</li><li><strong>Monitoring</strong>: Prometheus + Grafana + Loki + AlertManager stack</li><li><strong>Container Orchestration</strong>: Docker &amp; Kubernetes</li></ol><p>I’ll go over the interaction between these services briefly in this post, but I’ll create other posts where I will go deeper into certain parts of the architecture, like how I utilized the outbox publisher pattern, scaling the WebSocket server, and the RabbitMQ dead letter architecture used.</p><p>From the perspective of a user, they sign up or log in through the gateway-node service. First, the gateway-node service generates two tokens (A short-lived access token &amp; a long-lived refresh token). It hashes the access token along with certain properties and stores it in Redis to indicate the active session; it also properly stores the refresh token. The generated tokens are returned to the client, which in turn uses the access token to authenticate with the WebSocket server; at the point of authentication, the WebSocket server only needs to check Redis to confirm that the session is active. Hey, pause, I know my head is screaming:</p><blockquote>“What happens when the session is no longer active?”</blockquote><p>Since users have to subscribe to get notification updates for a particular task, we can just check for the active session before subscribing them to a task. That’s all for the user authentication section.</p><p>Once authentication is done, the client can request to create tasks. Three types of tasks exist, namely resize-image, compress-video, and generate-pdf (generates PDF from web pages).</p><pre>{<br>    &quot;type&quot;: &quot;resize-image&quot;,<br>    &quot;payload&quot;: {<br>        &quot;imageUrl&quot;: &quot;https://images.unsplash.com/photo-1522202176988-66273c2fd55f&quot;,<br>        &quot;width&quot;: 400,<br>        &quot;height&quot;: 300<br>    }<br>}</pre><p>Once a task creation API request is sent, an ID and traceID are generated and stored in PostgreSQL along with the task details.</p><p>The outbox-publisher polls the database periodically (adaptively, more details in a separate post) to fetch tasks that are not yet published to RabbitMQ, then publishes them to RabbitMQ. Tasks in RabbitMQ are queued up according to the different task types and are consumed by the different worker services.</p><p>Docker and Kubernetes (EKS) are used as part of the development and deployment infrastructure. Cluster and Pods autoscalers, which I’ll also discuss in subsequent posts, then metrics collection, monitoring, and observability using Prometheus, Grafana, Loki, Fluentbit &amp; AlertManager. Last but not least, load testing &amp; stress testing of the servers using Grafana K6 to see how well they perform under certain conditions.</p><p>This project is in no way meant to be perfect; rather, it’s solely for the purpose of allowing me to learn how to build a scalable distributed system, like any other budding engineer out there dreams of. Hopefully, things go well and something breaks … lol!!!</p><p><a href="https://github.com/oviecodes/taskforge">https://github.com/oviecodes/taskforge</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d67071710651" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My GSoC experience — AsyncApi Glee Authentication]]></title>
            <link>https://medium.com/@alecgee73/my-gsoc-experience-asyncapi-glee-authentication-f8c6df483f17?source=rss-823b77f2e9c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8c6df483f17</guid>
            <category><![CDATA[asyncapi]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[glee]]></category>
            <category><![CDATA[google-summer-of-code]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Alexander Godwin]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 07:31:54 GMT</pubDate>
            <atom:updated>2023-08-28T07:31:54.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>My GSoC experience — AsyncApi Glee Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGvrVsp3nYmj4Uu92Oxpng.jpeg" /><figcaption>Programming, software development</figcaption></figure><p>I am thrilled to provide an overview of my enriching experience during the Google Summer of Code (GSoC) 2023. Over the past 3 months, I had the privilege of contributing to the Postman organization, working on the AsyncApi Glee Framework. Throughout the program, I engaged in a variety of tasks and achieved significant milestones:</p><p>Project Overview: My project, Glee Authentication aimed to add an authentication layer to the Glee Framework. This authentication layer provides support for different authentication strategies implemented on the WebSocket and HTTP protocols. I collaborated closely with my mentors and the open-source community to ensure the project’s success.</p><p>Key Accomplishments:</p><ol><li>Task 1: WebSocket Authentication — The first task I took on was making provision for WebSocket authentication, the challenge faced in this stage was figuring out how WebSockets handles authentication and also the best method for authenticating WebSocket connections.</li><li>Task 2: HTTP Authentication — I faced a similar challenge as in the WebSocket authentication.</li><li>Task 3: Support different authentication strategies — I was able to bring a couple of the authentication strategies that AsyncAPI supports into Glee.</li></ol><p>Technologies and Skills: During the GSoC, I gained proficiency in various technologies and skills, including but not limited to:</p><ul><li>Typescript</li><li>AsyncApi</li><li>Testing</li><li>Documentation</li><li>WebSocket protocol</li><li>HTTP</li><li>Messaging systems</li><li>Glee</li></ul><p>Community Involvement: I actively participated in the AsyncApi community by attending meetings, and discussions. My interactions fostered a collaborative environment where I could seek guidance and provide assistance to fellow contributors.</p><p>Challenges Overcome: Throughout the program, I encountered challenges such as brainstorming on the best methods to support authentication in Glee, and initially not understanding the framework. I effectively addressed these challenges through consistent meetings with my mentors until we decided on the best methods moving forward.</p><p>Acknowledgments: I extend my heartfelt gratitude to my mentors, Souvik and Khuda, for their continuous support, guidance, and valuable feedback. Their mentorship played a pivotal role in my success.</p><p>Looking Ahead: As I conclude my journey with GSoC 2023, I remain committed to contributing to AsyncAPI and the open-source community. I am excited to continue building upon the foundation laid during this program and take my project to new heights.</p><p>I am excited about the future possibilities that lie ahead and will carry the experiences and knowledge gained during GSoC 2023 with me in all my future endeavors.</p><p>Here’s a link to the Glee authentication pull request: <a href="https://github.com/asyncapi/glee/pull/474">https://github.com/asyncapi/glee/pull/474</a></p><p>Here’s a link to the documentation of the new authentication feature: <a href="https://github.com/asyncapi/glee/tree/master/docs/auth">https://github.com/asyncapi/glee/tree/master/docs/auth</a></p><p>Here’s a link to the documentation pull request: <a href="https://github.com/asyncapi/glee/pull/507">https://github.com/asyncapi/glee/pull/507</a></p><p>Alexander Godwin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8c6df483f17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>