<?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 Patrik Valkovic on Medium]]></title>
        <description><![CDATA[Stories by Patrik Valkovic on Medium]]></description>
        <link>https://medium.com/@patrikvalkovic?source=rss-ac7bf31ff80c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8TxSGmFvMXwzMMAUqDRoJA.jpeg</url>
            <title>Stories by Patrik Valkovic on Medium</title>
            <link>https://medium.com/@patrikvalkovic?source=rss-ac7bf31ff80c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:46:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrikvalkovic/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[Messaging vs. Streaming: A Software Engineer’s Guide]]></title>
            <link>https://medium.com/qest/messaging-vs-streaming-a-software-engineers-guide-8500d97f6f25?source=rss-ac7bf31ff80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8500d97f6f25</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Patrik Valkovic]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 09:29:38 GMT</pubDate>
            <atom:updated>2025-08-18T22:20:42.339Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern software solutions face many challenges. We build distributed systems split into microservices, very often implemented by different teams. We have data pipelines that need to communicate without being tightly coupled. There are some non-technical challenges — users and management want to get insights into the data as early as possible, ideally immediately (think about recommendation systems or real-time dashboards). Websites serve millions of users every day, instead of a few thousand as before. How to tackle those problems?</p><p>Today I want to talk about messaging and streaming, related but by no means the same technologies. They try to solve some of the aforementioned challenges. I will be focusing mostly on RabbitMQ and Apache Kafka, the most prominent and widely used technologies out there. My goal is to introduce you to the general messaging and streaming patterns, how they work, and aspects in which they differ. I will also mention some of the pain points I came across during my professional experience with these technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmw67lwpYJY3EDeXlQGDcg.jpeg" /><figcaption>My name is Patrik Valkovič, solution architect, team leader, and advocate of engineering excellence. The rule I follow is “Clean code, clean conscience.”</figcaption></figure><h3>Asynchronous communication</h3><p>Let’s start with what both of them have in common — they are built on top of asynchronous communication. This requires a small shift in thinking, as I expect most of you are familiar with the traditional synchronous, HTTP-like type of communication. Synchronous communication has advantages that we lose — the calling application receives the response almost immediately, it knows the results and can work with the payload right away (including the errors that occurred, giving the users room to correct their mistake or let the application fix it for them). The familiarity among developers also plays an important role. There are some disadvantages I will talk about in a bit, but let me first introduce you to asynchronicity.</p><p>Asynchronous communication uses messages to communicate — some content that the application (called publisher) sends to other applications through the broker. The broker is responsible for storing the message for a sufficient time and delivering it to the application the message is supposed to go (both RabbitMQ and Kafka are brokers). The receiving application (called a consumer) will ask the broker for messages, and after the broker delivers them, the application can do its job. The application can create and publish more messages as a response to the one it received, making the application both publisher and consumer. The message may be in any format the applications can process, such as binary, JSON, or Protobuf. From the perspective of the broker, the message is just a blob of bytes. The important aspect is that there is no direct invocation and no immediate answer; everything goes through the broker.</p><p>Before moving on, note that although HTTP communication is synchronous and messaging/streaming is asynchronous most of the time, it doesn’t need to be. The type of communication is based on design, not driven by technology. You can turn HTTP into asynchronous communication by returning the 202 Accepted status code and letting the client poll for changes. Similarly, the application sending the message can instruct the consumer where to publish response, making the communication synchronous (although with a bit more effort, I must admit that). This pattern is often called Remote Procedure Call (RPC).</p><p>So what are the advantages? Why go the extra mile?</p><ul><li><strong>Reliability</strong> — the broker stores the messages as long as necessary, working as a buffer between the producer and consumer. The consumer may be overwhelmed or not even be running at the time the publisher sends the message. Once the consumer has enough capacity or is available, it will process the message at its own rate.</li><li><strong>Scaling</strong> — related to the previous point, the consumer doesn’t need to be scaled up to handle a sudden peak of messages. The messages are kept in the broker, allowing retroactive scaling. The system spawns a new instance only when there is work for it to perform, saving the infrastructure from over-scaling and saving in costs.</li><li><strong>Decoupling</strong> — The broker acts as a middleware between the producers and consumers. The producing application has no knowledge of the consuming applications — it doesn’t know where they are running, in what technology, or even how many of them exist. Consider a user registration event, I will use it as an example — the system needs to send a welcome email, create a record in the CRM, provision user resources, and notify an analytics service. In a synchronous, HTTP-based system, the registration service would need to make individual calls to each of those downstream services. The complexity will further grow as more consumer services are added. Now, imagine two services where the user can sign up; the complexity multiplies. With a message broker, the registration service simply publishes a single UserRegistered event. Any service interested in this event can subscribe to it and react accordingly. The producer is completely shielded from the complexity of the downstream ecosystem, leading to a more resilient and maintainable architecture.</li></ul><p>I will start with messaging, as it is conceptually easier to understand. Then, I will follow with streaming and comparison of the two.</p><h3>Messaging</h3><p>Messaging is one flavor of asynchronous communication. The most prominent service out there is RabbitMQ. The publisher sends the message or event in so-called record — data structure containing the message and metadata like encoding, authorization, when the message was sent, etc. One important piece of metadata is the type of message (in RabbitMQ called routing key) — but more on that later. The publisher sends messages to the queue, and the consumers read them. Once the message is processed, it is deleted from the queue. The broker then handles all the heavy lifting in between.</p><p>The broker handles message coordination and many problems for us. The most important ones are:</p><ul><li>Physically saving the messages in queues in case of hardware failure or network partition. Once the system recovers, consumers can safely process messages received before the failure.</li><li>Matching messages to consumers, making sure the message is sent only to a single consumer at a time. This ensures there aren’t duplicates in the system.</li><li>Deleting processed messages from the queue once the consumer acknowledges their successful processing. This is important; the sentence implies two important distinctions from streaming — the consumer must explicitly acknowledge the message, ideally after it is processed, not after it receives it (because of failure handling, more on that in the following point). Secondly, the message is deleted after it is processed.</li><li>The message processing can fail because of various reasons — a bug in the consumer, its crash, or maybe contention of the database during processing of the message. The broker is responsible for retrying failed messages — sending them again, possibly to a different consumer instance.</li></ul><p>These processes are important, as they make the system reliable by making sure no messages are lost and processed only once if possible.</p><h3>Messages Routing</h3><p>When you recall the example from the beginning, I wanted a single message (the UserRegistered event) to be processed by multiple consumers—one to send a welcome email, one to update the CRM, and another for analytics. But as I’ve written, a standard queue delivers each message to only a single consumer and deletes it afterwards. So how do we implement this one-to-many pattern? That is where <strong>exchanges</strong> come into play.</p><p>In RabbitMQ, a producer does not publish a message directly to a queue. Instead, it sends the message to an exchange. The exchange acts as a smart routing agent. It receives the message and, based on its type and a set of rules, determines which queue(s) should receive a copy of the message. This routing logic is based on message metadata, the most common is the <strong>routing key</strong> (describing message type, e.g., user.registered.eu). The rules are encoded in what RabbitMQ calls <strong>bindings</strong> - how queues bind to exchanges.</p><p>To implement the user registration pattern, I’d use a fanout type of exchange. It simply broadcasts every message it receives to all queues that are connected to it. I would create three separate queues: email_queue, crm_queue, and analytics_queue. Each service would consume from its respective queue. By binding all three queues to our fanout exchange, a single UserRegistered message published to that exchange gets copied and delivered to all three queues simultaneously, achieving the desired one-to-many delivery.</p><p>The entire structure of exchanges, queues, and the bindings that connect them is known as the <strong>topology</strong>. Defining a clear and logical topology is a major part of designing a messaging-based distributed system. It represents how information flows through the system and is great for achieving the right communication patterns, whether it’s simple work distribution or complex choreography of queues, exchanges, and services. You can see topology of the system I work on below, it should give you some general idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoZnN0vpBREkZPm7psP67g.png" /></figure><h3>Messaging Brokers</h3><p>So far, I’ve talked mostly about RabbitMQ, but it is not the only representative out there. The landscape is rich with alternatives, each having its own strengths and weaknesses:</p><ul><li><strong>AWS SQS and SNS:</strong> If you are using Amazon Web Services, you are probably familiar with Simple Queue Service (SQS) and Simple Notification Service (SNS). You can combine these two services to achieve results very similar to RabbitMQ — using an SNS topic in place of an exchange and SQS queues as, well queues. SNS handles the message routing (supporting both one-to-many and fanout patterns), and SQS provides the durable queuing for consumers.</li><li><strong>Apache ActiveMQ:</strong> Veteran in the messaging space, ActiveMQ is an open-source broker that supports multiple protocols, including AMQP, STOMP, and MQTT. It’s known for its flexibility and adherence to the Java Message Service (JMS) standard.</li><li><strong>NATS:</strong> A newer, lightweight, and extremely high-performance messaging system. While at its core is a simple and fast pub/sub model, its newer JetStream component adds persistence and streaming capabilities, making its way into both messaging and streaming.</li><li>Other major cloud providers offer their own managed messaging services. Google Cloud Pub/Sub provides a globally scalable event ingestion and delivery system, while Azure Service Bus offers reliable messaging as a service with queues, topics, and advanced features like sessions and duplicate detection.</li></ul><h3>Drawbacks of Messaging</h3><p>Messaging is very powerful, but the design choices behind the architecture introduce certain trade-offs you need to be aware of. Here are some I identified during my work with RabbitMQ:</p><ul><li>Messages are deleted after they are successfully processed. This is efficient for task-based work, but what if a bug is discovered in a consumer <em>after</em> thousands of messages have already been processed incorrectly? The original messages are gone. Regenerating them can be difficult, often requiring complex fixes like recreating messages from application logs or re-running batch jobs. And you are still on the better side; the source data may not even be available anymore.</li><li>To prevent data loss from a single machine failure, the solution needs to be highly available. In RabbitMQ, this is achieved with <strong>Quorum Queues</strong> that replicate messages across at least three nodes in a cluster. While this ensures durability, it means that for every published message, its content is written to disk three times and sent over the network at least four times (but can be up to six times) <strong>for every queue</strong>! For high-throughput systems, this replication overhead can significantly increase storage costs and, more importantly, consume substantial network bandwidth, potentially becoming a bottleneck.</li><li>Poison Pill<strong>:</strong> A message that a consumer can never successfully process — due to a malformed payload or a consumer bug — is known as a “poison pill”. If not handled properly, this message can get stuck at the head of a queue. The broker will deliver it, the consumer will fail, the message will be re-queued, and the cycle will repeat endlessly (because the message is kept at the head of the queue). This not only wastes consumer resources but can have deadly consequences for the broker itself. In RabbitMQ, these repeated failures build up the internal Raft log (a distributed transaction log), which can degrade the performance and, in extreme cases, destabilize the entire cluster. Note that a similar impact can also occur with a message that was processed but not properly acknowledged by the consumer.</li></ul><p>To combat the poison pill problem, the most common solution is the <strong>Dead-Letter Queue (DLQ)</strong> pattern. You can configure a queue to redirect a message to a special queue after a set number of failed delivery attempts — effectively isolating the problematic message. The main queue gets rid of the message and can continue to process healthy messages. Developers can then manually inspect the messages in the DLQ and diagnose and fix the underlying issue without impacting the live system.</p><h3>The Shift to Streaming</h3><p>Where messaging is about sending events, I find streaming is about capturing and storing facts. A stream is not a queue of things to do; it is an <strong>immutable, ordered, and replayable log of events</strong>. Stream is, in some sense, a combination of a queue and persistent storage — the record remains in the stream until it expires (called retention period). The record can’t be modified (hence the immutability), you need to publish a new record with an updated payload. And because the records are stored in the stream, you may replay them even after the record has been processed. You can think of a streaming platform as a distributed transaction or commit log, as a file to which I can only ever append.</p><p>This leads to the most profound difference from messaging: when a consumer reads an event from the stream, the event is <strong>not deleted</strong>. This means the log of events can be re-read as many times as desired by as many different consumers as needed, all at their own pace, without the need to duplicate the messages. A new analytics service I deploy tomorrow can start reading from the beginning of time to build up its state, something that is impossible in a traditional messaging system.</p><h3>Mental model of streaming</h3><p>The messaging model was conceptually easy, at least from the perspective of your application — you send messages to the broker and consumers read data from their respective queues. For streaming, I need to go a bit deeper. I will base the following text on Apache Kafka concepts and terminology, as it is the most well-known streaming platform out there. But even when the terminology may differ across platforms, the concepts remain the same for other alternatives out there.</p><p>Kafka organizes data into <strong>topics</strong> (e.g., user-clicks), which are split into one or more <strong>partitions</strong>. You can think of a partition as a slice of the topic, it contains a subset of messages and is the key to Kafka’s parallelism. Each partition can be further replicated - copied across multiple nodes, ensuring high availability when one of the nodes goes offline. The replication factor is configured at the topic level.</p><p>Let me now focus on the publisher application. For messaging, the logic was easy — just send a message to the broker with a proper routing key. In streaming, the publisher itself must decide which specific partition to send the message to; the decision is entirely in the publisher’s hands. This is most often done by providing a <strong>routing key</strong> with the message. The publisher logic then uses this key to determine the destination partition, typically by hashing the key and mapping it to a partition. The messages should be ideally uniformly distributed across all partitions to avoid “hot partitions” that become performance bottlenecks. Typically, all events for a specific entity (e.g. user) should be processed in the exact sequence as they occurred, and they must be sent to the same partition (otherwise the order is not guaranteed). This is achieved by using the userId as the routing key. Some managed solutions can simplify this; for example, Amazon Kinesis Data Streams uses a partition key (equivalent of routing key), hashes it, and automatically assigns the message to the correct partition (or &quot;shard&quot;) for you.</p><p>Now for the other side — the consumers. Since messages are not deleted from the log, the consumer must track which messages it has already processed; the broker doesn’t do it for you. This progress is tracked by an <strong>offset</strong> of the last processed message within a partition. The consumer is responsible for committing this offset back to the broker periodically. Again, most often done by writing to a special internal Kafka topic, but any other solution, like storing it in a database, can be used. How and when the consumer commits its offset has a direct impact on throughput and consistency. Committing too often decreases throughput, while committing too late can cause duplicate processing (in case of consumer crash).</p><p>To parallelize the work, multiple instances of a consumer application operate as a <strong>consumer group</strong>. Kafka guarantees that each partition is consumed by exactly one consumer within a group. If I have a topic with 10 partitions and I deploy 10 instances of my service in a single consumer group, each instance will handle exactly one partition. If I deploy a second, completely separate service (a different consumer group), it too can read from all 10 partitions in parallel, without interfering with the first group. But if I spawn more instances than that, the remaining ones will sit idle, as there are no more partitions they could process. The number of partitions, therefore, directly controls the maximum parallelism of the system.</p><p>Changing the number of partitions after the topic creation is challenging. After adding new partitions, the publisher’s routing logic must reflect the change. A message for a specific user that previously went to partition A might now be routed to a new partition B, potentially causing events for that user to be processed out of order. This doesn’t need to make problems for some applications, but it can have an impact on others. While possible, deleting partitions is nearly impossible without significant disruption. For example, Kinesis Data Streams solves this by creating a barrier where the consumers wait until all of them catch up.</p><h3>Drawbacks and comparison to Messaging</h3><p>While streaming is a powerful concept, often outperforming messaging solutions, it has some drawbacks, and you should consider them before making the decision.</p><ul><li>Upfront Planning is Critical: Because changing the number of partitions is an expensive and potentially disruptive operation, you must plan your capacity needs in advance. You need to estimate the future throughput of the system to choose a partition count that will be sufficient for the foreseeable future, as correcting later is difficult.</li><li>“Smart Client” Complexity<strong>:</strong> The logic for partitioning messages and tracking processed offsets resides entirely on the publisher and consumer side. This leads to the “smart publisher/consumer, dumb broker” paradigm. This complexity multiplies as the number of services grows; for example, a change in the routing strategy must be carefully propagated to every single publishing service to maintain consistency.</li><li>Consumer Rebalancing<strong>:</strong> When a consumer instance is added to or removed from a consumer group (due to scaling, deployment, or a crash), the group must rebalance. The consumers temporarily stop processing messages while they renegotiate the assignment of partitions. This rebalancing can cause a noticeable pause, temporarily decreasing the overall throughput of the system. From this perspective, messaging solutions handle scaling more smoothly.</li><li>Storage Requirements: The persistent nature of the streaming requires storage. Since messages are retained for a configured period (from hours to months or years), the cluster must have enough disk capacity to store the entire volume of messages for that duration. This can lead to significantly higher storage costs compared to a messaging platform where messages are ephemeral.</li><li>No Routing: The broker itself provides no routing logic. A producer sends a message to a specific topic, and consumers read from that topic. This creates a higher coupling between services compared to the flexible exchange-based routing in RabbitMQ. If a consumer needs data from multiple topics, it must explicitly subscribe to and manage consumption from each one.</li></ul><h3>Other streaming platforms</h3><p>Although I have focused mostly on Kafka, it is by no means the only solution out there. The streaming market is full of alternatives:</p><ul><li><strong>Amazon Kinesis Data Streams:</strong> As mentioned, this is the direct AWS equivalent to a self-managed Kafka cluster. It provides a fully managed, scalable, and durable real-time data streaming service, where you manage “shards” instead of partitions.</li><li><strong>Azure Event Hubs:</strong> Microsoft’s offering of a highly scalable data ingestion service. It integrates tightly with the Azure ecosystem and provides a Kafka-compatible endpoint, allowing you to use existing Kafka applications with minimal changes.</li><li><strong>Google Cloud Pub/Sub:</strong> While also a capable messaging service, Pub/Sub is designed for massive scale and can be used as a streaming backbone.</li><li><strong>NATS JetStream:</strong> Building on the high-performance NATS messaging core, JetStream adds the persistence layer required for true streaming. It offers replayability and consumer state tracking, positioning itself as a modern, simpler alternative to Kafka.</li><li><strong>RabbitMQ Streams:</strong> RabbitMQ now has its own implementation of streaming in Streams and Superstreams (partitioned streams). They become part of mainstream distribution from version 3.9, superstreams a bit later in version 3.11. If you are already using RabbitMQ, this may be a viable option if you don’t want to manage different platform.</li></ul><h3>Brief comparison</h3><p>In summary, you should now have a general understanding of how messaging and streaming work and how they differ from each other. Here is a quick overview summarizing the topics I covered so far.</p><ul><li><strong>Core Idea:</strong> Messaging is for delegating tasks or sending events; messages are work items that get deleted after being processed. Streaming is for capturing facts; they are permanent records in a replayable log that persist even after being read.</li><li><strong>The Broker’s Role:</strong> In messaging, the broker is “smart,” handling message lifecycle and complex routing logic via exchanges and bindings. In streaming, the broker is “dumb,” acting simply as a durable, partitioned log file.</li><li><strong>The Client’s Role:</strong> Messaging clients are relatively simple, as they simply process what the broker delivers to their queue. Streaming clients are “smart,” responsible for deciding where to publish messages (partitioning) and tracking their own reading progress (offsets).</li><li><strong>Data Lifecycle &amp; Replayability:</strong> Messages are ephemeral and deleted after successful processing, making replay impossible. Streamed events are persistent for a configured retention period and can be re-read multiple times by different services.</li><li><strong>Flexibility vs. Performance:</strong> Messaging offers high flexibility with its powerful routing capabilities, but this can introduce overhead. Streaming prioritizes raw throughput and scalability, which requires more upfront planning and shifts complexity to the client applications.</li></ul><h3>Making the Right Choice</h3><p>A few closing words from my side. How to make the correct decision on which of the two approaches to choose?</p><p>I consider a <strong>messaging system</strong> like RabbitMQ when the goal is to reliably delegate tasks (e.g. to a background worker) or notify the rest of the system about changes in the system using events (e.g. user registration). Those are use-cases when I don’t need replay capabilities and the simplified interaction with the broker is more important to me. Guarantees and routing capabilities inside the broker are great to decouple services and allow me to expand the system without modifying existing code.</p><p>I use <strong>Streaming platforms</strong>, like Kafka, to process and analyze the flow of records, possibly even in real-time (e.g. for auditing or detecting fraudulent activities). I use streaming every time I need to make messages as a data source for other services. In those situations, replay capability is the most important feature the streaming brings to the table. Because of the “dumb broker” paradigm, streaming can also achieve higher throughput, making it the way to go for high-traffic websites and applications.</p><p>Finally, let me note that these two patterns are not mutually exclusive. In fact, they can coexist peacefully in a single architecture. I might have a Kafka stream processing application that analyzes a continuous flow of IoT data and, upon detecting an anomaly, produces a message to a RabbitMQ queue to trigger a specific, transactional task, like dispatching a technician.</p><p>That is all from me today, I hope you enjoyed the article and learned something new today. By the way, did you know that Kafka is named after the author Franz Kafka?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8500d97f6f25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qest/messaging-vs-streaming-a-software-engineers-guide-8500d97f6f25">Messaging vs. Streaming: A Software Engineer’s Guide</a> was originally published in <a href="https://medium.com/qest">Qest technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ECS scale to zero using CloudFront]]></title>
            <link>https://medium.com/qest/ecs-scale-to-zero-using-cloudfront-8b7dcb61b59b?source=rss-ac7bf31ff80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b7dcb61b59b</guid>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <dc:creator><![CDATA[Patrik Valkovic]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 05:36:04 GMT</pubDate>
            <atom:updated>2025-03-06T05:36:04.239Z</atom:updated>
            <content:encoded><![CDATA[<p>At the age of the cloud, scale to zero is a great opportunity to save some costs on your environment. Dockerized applications have become the standard way of deployment these days, but, unlike serverless computing, the possibility of turning the infrastructure off during times without any traffic is still a bit challenging. Other cloud providers, such as Google Cloud and its <a href="https://cloud.google.com/run/docs/about-instance-autoscaling">Cloud Run</a> service, have scale-to-zero built-in, making it easy to use without much effort. I wouldn&#39;t be surprised if Amazon Web Services introduced similar functionality, it is really a standout feature and a reason for some companies to choose Google over AWS (take that with a grain of salt as I don’t have any inside knowledge from the ECS team). But we don’t need to wait. As is often the case with Amazon Web Services, you can connect multiple services together to achieve suchlike functionality. Today I will explore how CloudFront can be used to automatically scale ECS services to zero and start it up when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*679T6efH_ZpoyvUuEQFuiA.jpeg" /></figure><h3>What does scale to zero mean?</h3><p>Scale to zero is built on the concept of auto-scaling. Traditionally, auto-scaling refers to the ability of the app or service to increase or decrease its capacity based on the demand —often determined by the number of active users currently visiting your website. It can also involve scaling workers based on the work queue length or processing delay. Scale to zero, as the name suggests, takes this idea further by allowing an application to shut down completely (when there are no requests) and start up when the first user hits your website.</p><p>For this post, I will focus on a dockerized HTTP service running inside <a href="https://aws.amazon.com/ecs/">Elastic Container Service</a>, since that is the most common use case today. Unlike event-driven architectures, where the message in the queue may wait for a while, HTTP is synchronous — requests to the service are expected to return an answer almost immediately. This introduces an extra challenge: <em>something</em> (and I will describe what further down) needs to “hold” the connection open while the container starts up and before it is ready to answer. Google Cloud Run handles this natively and the functionality is ready for you to use, in AWS we will need to implement it ourselves.</p><h4>Why should you care?</h4><p>The biggest benefit is cost savings, especially for environments where some latency is acceptable. This typically includes development or testing stages where the services are used sporadically — mostly during working hours. Scaling to zero can cut your charges by 50 %.</p><p>You might argue that ECS already has scheduled scaling policies, you may configure them to start the service at 08:00 and stop it at 20:00 on working days only. But these schedules are rigid — what if some developer was at the dentist and wanted to work late? Using scale to zero gives you more flexibility, as the service starts automatically when it is and shuts down automatically after the work is done.</p><h3>Architecture</h3><p>I will use a standard backend architecture for containerized applications:</p><ul><li>ECS on top of Fargate chosen for its faster startup time, thus reducing the perceived latency by the user. While EC2-hosted ECS services could work, you must account for the delay in starting the instance, its registration as a container instance, and the container startup itself. By using Fargate, you eliminate all these delays except the container startup.</li><li><a href="https://aws.amazon.com/elasticloadbalancing/application-load-balancer/">Application Load Balancer</a> (ALB): acts as the public-facing entry point and routes traffic to the service.</li><li><a href="https://aws.amazon.com/cloudfront/">CloudFront</a>: for now configured as a simple pass-through proxy, but later used to facilitate the scale-to-zero mechanisms. It will be responsible for starting the container and keeping the in-flight HTTP connection open.</li></ul><p>You can find the diagram with the complete architecture in the repository with the source code.</p><h3>Step 1: Turning the Application Off</h3><p>Let&#39;s start with the easier step, shutting down the application when idle is relatively straightforward — I will use CloudWatch alarm to shut down the application when there is no traffic (in other words, scaling it to zero).</p><p>AWS CloudWatch provides a RequestCount metric for target groups within the ALB namespace, telling you how many requests a load balancer has received. By creating a CloudWatch alarm that monitors this metric, we can trigger an ECS scaling policy to set the number of replicas to zero when no requests are detected for a specified period (e.g. 10 minutes).</p><p>Implementation details:</p><ul><li>Ensure the alarm resolution is not lower than the metric resolution (typically 1 minute), or the alarm will stay in an “INSUFFICIENT_DATA” state.</li><li>Use a threshold value of zero with a &lt;= comparison operator. There isn’t an equality comparison operator.</li><li>AWS CDK does not support simple scaling policies through high-level constructs, so you’ll need to manually create a CfnScalingPolicy (full source code is linked at the end of the post).</li><li>Use absolute values (not percentages) when setting the desired number of tasks. Otherwise the policy may not shut down the task.</li></ul><p>Once set up, your service will automatically scale down when idle. Half the job is done! Now, how do we bring it back to life?</p><h3>Step 2: Start the application on request</h3><p>When you now try to access the application, you will get an HTTP 503 Service Unavailable. That makes sense, as there are no containers to process that request. This is where CloudFront comes into play.</p><p>CloudFront has a feature called <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/high_availability_origin_failover.html">Origin Groups</a>, designed to handle request errors and failover. When configured, it routes all the requests to the designated primary origin (our service). If a request fails, CloudFront automatically retries it with the failover origin. The decision, whether to invoke the failover origin, can be further controlled by the type of error received from the primary origin. In our case, a <a href="https://aws.amazon.com/lambda/">Lambda</a> function will be triggered when the primary origin returns a 503 response code. Here is a description of the whole process:</p><ul><li>CloudFront forwards the request to the primary origin.</li><li>When CloudFront detects a 503response, it forwards the request to a Lambda function instead.</li><li>The Lambda function checks the ECS service and sets the desired task count to 1, but only if it’s currently 0 (to prevent redundant updates from parallel requests).</li><li>The Lambda function waits for the ECS task to start.</li><li>Once the task is running, it resends the original request via CloudFront (which should now call the started task), and proxies the response back to the user.</li></ul><p>Subsequent requests go directly to the ECS service (the CloudFront primary target), bypassing the Lambda function. And that is all the magic needed.</p><p>During my testing, the Fargate task usually <strong>started in around 35s</strong>. It is slower than if native implementation by the ECS is used (for comparison, the Cloud Run task usually takes about 13s to start), but still reasonable.</p><h3>Drawbacks</h3><p>There is one limitation I didn’t mention yet. CloudFront is a Content Delivery Network, and we can’t forget that. Because of the use of Origin Groups, only GET, HEAD, and OPTIONS methods are supported. Since POST and other methods usually modify server state, and there is no guarantee of them being idempotent, they can’t be safely retried by CloudFront. The workaround is to implement a kind of health endpoint that will start up the application and will be called by your application (or manually) before any other operations. To support other HTTP methods, use multiple behaviors on the CloudFront level. This variant is not implemented in the example app, as it dependens on your use case.</p><p>A softer limitation is CloudFront response timeout of 90 seconds. If ECS is slow to start, the function can keep hanging, forcing CloudFront to return connection time out error to the user (no matter the timeout setting of the Lambda function itself). But a simple refresh should work once the service starts up. Increasing the timeout is possible but it may require contacting AWS support.</p><h3>Alternatives</h3><p>The limitation to read-only HTTP methods may not suit everybody. There are alternative ways of combining AWS services to achieve the functionality.</p><ul><li>Using Route53 failover record type. Instead of using CloudFront, Route 53 can direct traffic to different origins based on CloudWatch alarms. When the service is down, it can reroute requests to a Lambda function that initiates ECS. However, this brings other drawbacks such as requiring a short TTL setting so clients catch up with the changes fast. This brings a number of DNS requests (and possibly charges for them) up. There is a generous free tier for Route53, so I don’t expect this would be a significant issue.</li><li>Using Application Load Balancer using <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html">weighted</a> target groups. Though primarily designed for traffic distribution, it might be possible to adapt it for failover and scale-to-zero functionality.</li></ul><p>Each of these alternatives has trade-offs in terms of latency, complexity, and operational overhead. I haven’t explored these yet, but if any of them sound interesting, subscribe and be notified when I dive deeper into them in a future post!</p><h3>Source code</h3><p>The sample application is a simple nginx container, but you can replace it with your own containerized application. Just keep in mind that image size and startup time will affect latency.</p><p>The deployment is fully automated using Cloud Development Kit implemented in TypeScript. You can find the full source code and architecture diagram on GitHub: <a href="https://github.com/PatrikValkovic/ecs-scale-to-zero">https://github.com/PatrikValkovic/ecs-scale-to-zero</a>.</p><h3>Conclusion</h3><p>By combining ECS, CloudFront, and Lambda, we can achieve scale-to-zero behavior without native AWS support. While it’s not as seamless as Cloud Run, it’s a viable solution for cost-conscious environments where occasional startup delays are acceptable.</p><p>Would you try this approach in your own infrastructure? Have you explored other ways to scale ECS services to zero? Let me know your thoughts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b7dcb61b59b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qest/ecs-scale-to-zero-using-cloudfront-8b7dcb61b59b">ECS scale to zero using CloudFront</a> was originally published in <a href="https://medium.com/qest">Qest technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncle Bob’s Clean Code — is it still relevant?]]></title>
            <link>https://medium.com/qest/uncle-bobs-clean-code-is-it-still-relevant-614c71d98748?source=rss-ac7bf31ff80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/614c71d98748</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrik Valkovic]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 14:06:49 GMT</pubDate>
            <atom:updated>2025-01-21T14:06:49.366Z</atom:updated>
            <content:encoded><![CDATA[<h3>Uncle Bob’s Clean Code — is it still relevant?</h3><p>Over the Christmas holidays, I had some time off from work and wanted to step away from monitors for a bit (but only a little). So, I decided to catch up on some books I had been meaning to read for a while. One of those was the <em>Clean Code</em> by Robert C. Martin (aka Uncle Bob). This book is often hailed as “the most important book every developer should read” or the “holy grail” of software engineering. Intrigued, I decided to give it a try and read through it, so you don’t have to (unless you want to, of course). My main curiosity was whether it still holds relevance today, considering the book was published back in 2008. To put that into context, it was the era of PHP 5.2, Java SE6, Internet Explorer 7, and the early days of the iPhone. So, has the <em>Clean Code</em> stood the test of time?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*g9UZbv8SPUJ_asT6l_MO9A.jpeg" /></figure><h3>What the book is about?</h3><p>At its core, <em>Clean Code</em> is about writing good code — and good code, as Uncle Bob argues, must be clean code. But it’s more than just coding style or best practices. Throughout the book, there’s a strong emphasis on professionalism, or what Bob calls “craftsmanship.” He encourages developers to approach coding as both an art and a serious responsibility, rather than merely a means to earn money.</p><p>The book begins by exploring the concept of clean code: What is it? How do we recognize it? Why is it important? Uncle Bob argues that clean code goes beyond syntax and aesthetics, it anticipates future changes. He emphasizes how clean code makes development faster and more enjoyable, while bad code can slow you down and lead to frustration.</p><p>From there, the book dives into pretty standard topics, such as naming variables, function composition, designing classes, and data structures. Each chapter builds on the previous one, gradually expanding the scope from writing a single line of code to architecting entire systems. One chapter I liked dealt with third-party libraries and services, emphasizing the importance of their abstraction to reduce coupling and ensure maintainability.</p><p>The concept I liked about it was the idea of “learning tests.” These are tests you write to understand how a library or API behaves. By writing these tests, you make sure you understand the library, how it should be called, and ensure that it works the way you expect it to. As Uncle Bob notes, “We have to learn the API anyway,” so why not document that learning through tests? I believe you can exclude them from CI/CD pipelines and standard test suites because they serve as documentation and for a developer’s practice, ensuring the library behaves as expected. For example, sending an email every time you run tests is probably not the brightest idea. Even better, you can condition those tests using flag or environment variables, allowing you to run them when you see fit. One such great case is after upgrading your dependencies, allowing you to check for breaking changes.</p><p>The book also dedicates a chapter to concurrency, along with an appendix on the subject (that’s how much Uncle Bob tries to warn us). He highlights just how tricky concurrent programming can be. If you’ve ever worked with multi-threaded applications, you’ll understand the challenges. And if you haven’t, consider yourself lucky. These chapters provide a high-level overview of common pitfalls and emphasize the need for caution when dealing with concurrency — a topic that definitely deserves a book of its own.</p><p>The book concludes with three projects (or rather code snippets) where Uncle Bob applies his principles to real code. These examples show you, step by step, how to refactor messy code into clean code. Not only that, Bob gives insights into why he changed the code the way he did and what it will bring us. The final chapter includes a “smells” list: common patterns that developers should watch out for, as they often indicate deeper issues within the codebase.</p><h3>What Would I Adjust for the Modern Environment?</h3><p>One topic I find noticeably absent from Clean Code is immutability, a programming style where variables and objects are treated as constants — modifications to objects are minimized or avoided completely. Instead of changing an attribute of an existing instance, the immutable approach creates a new instance with the updated attribute. The key advantage is, in my view, its ability to reduce side effects. Imagine passing an object to a function, only to have that function modify the object in some way. Now consider a worse scenario: the code that alters the object is added later as part of a different feature. This introduces “collision” between the caller, who assumes the object remains unchanged (and for example may store the attribute into a local variable), and the callee that modifies it. The result? Bugs that can take days to track down. And the scariest part? There is no way to reliably detect such issues.</p><p>You might argue that immutability introduces performance overhead — after all, creating a new instance for every modification does come with a cost. This is a valid concern, but I think that for most of the applications we work with nowadays (excluding highly constrained environments like microprocessors or real-time systems), the trade-off is worth it. Bugs are often far more expensive to debug and fix than the cost of scaling infrastructure to handle minor performance overhead. As an added bonus, immutability makes multi-threading much easier (remember that there is a dedicated chapter and appendix just for that).</p><p>Another area I personally find overly strict is the guidelines on functions. Bob suggests that functions should ideally be no longer than few (five or so) lines. In the end, it feels like the function should have at most a single if statement or try-catch block. This can result in cluttering a namespace with functions like doSomething, doSomethingCached, or safeDoSomething , making it harder to work with, especially when IDE suggests multiple similar-sounding functions as you start typing. Instead, I prefer functions that are long enough to maintain clarity and context while still fitting comfortably on my screen (with my increased font size this translates to around 27 lines). This balance, in my view, offers better readability and minimizes unnecessary complexity.</p><p>Formatting is another topic that I think has evolved since 2008. Today, many languages come with built-in formatters (e.g., gofmt for Go, rustfmt for Rust), or has dedicated tools like Prettier and ESLint for JavaScript and TypeScript. These tools aren’t perfect, I came from the Node.js ecosystem, and I’ve personally moved away from Prettier (to Eslint stylistic rules) because I couldn’t configure it to align with my preferences. Nevertheless, the tools still help enforce consistency, which is far more valuable than adhering to any particular coding standard. That said, the points raised in the book, such as using vertical spacing, are still important and are not addressed by linting or formatting tools.</p><h3>Should you read it?</h3><p>After much thought, my answer is: probably not. Let me explain. It’s not that the content is inaccurate — quite the opposite, I align with almost everything Uncle Bob discusses.</p><p>Firstly, I suppose you’re considering picking up this book. In that case, it’s likely because you already care about writing readable, high-quality code and have a few years of programming experience under your belt. You are a professional, who understands that poorly-written code, although working, is not yet finished. So by now, many of these lessons may already feel familiar, learned firsthand as you navigated the challenges of real-world development. You know (and understand why) functions and methods should be short and variables should have meaningful names — or at least try your best.</p><p>That said, it might still be worthwhile to skim through the book. It could help you identify blind spots or areas where your understanding could be refined — e.g. when you are junior, the book can be quite eye-opening. However, I wouldn’t suggest committing significant mental energy to it.</p><h3>What to read instead?</h3><p>I highly recommend <em>The Clean Coder</em>, a spiritual sequel to <em>Clean Code</em> as well by Uncle Bob. Despite the similarities in the title, its focus is entirely different — it delves into the professionalism of being a software developer (as Bob wants us to be) and is very little about the code.</p><p>This book addresses topics such as time management, dealing with pressure, communication with stakeholders, and responsibility (there is more to it than you would guess!) One of its standout chapters is on estimates — the perpetual conflict between the developers and business people. It clarifies the distinction between estimates and commitments while giving possible approaches for making reliable predictions.</p><p>At just over 200 pages, it is a powerful read that still, ten years later, offers great insights for software developers. It makes you realize that the job is not just about the code but encompasses a range of other responsibilities. If you’re looking to elevate your approach to the <em>craft</em>, this book is a must-read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMckSdukwvj9Km3UCjIAEg.png" /></figure><h3>Farewell</h3><p><em>Clean Code</em> has its merits, and its principles remain as relevant today as they were at its publication. If you are considering reading it, chances are you already have a solid grasp of these concepts. That said, it may reinforce what you already know and practice. Skimming the book for areas you might not have considered and moving directly to <em>The Clean Coder</em> could be, in my opinion, more productive. Ultimately, the best way to grow as a developer is still by writing code, making mistakes, and learning from them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=614c71d98748" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qest/uncle-bobs-clean-code-is-it-still-relevant-614c71d98748">Uncle Bob’s Clean Code — is it still relevant?</a> was originally published in <a href="https://medium.com/qest">Qest technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Advent of Code 2024 and what did I take from it]]></title>
            <link>https://medium.com/qest/the-advent-of-code-2024-and-what-did-i-take-from-it-4e1b7e5b0199?source=rss-ac7bf31ff80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e1b7e5b0199</guid>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[advent-of-code]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Patrik Valkovic]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 14:43:16 GMT</pubDate>
            <atom:updated>2025-01-03T14:43:32.994Z</atom:updated>
            <content:encoded><![CDATA[<p>For those who don’t know, Advent of Code (AoC) is an annual programming competition where participants solve daily puzzles throughout December using a programming language of their choice. In previous years, I’d always started strong but never made it to the end. This year we started a private leaderboard with my colleagues that kept me motivated (I am not competitive, YOU are!) My ego pushed me through the days. I managed to complete all 25 days, and I want to share my thoughts on the experience.</p><p>To make things more interesting, I decided to use Rust, a language we all hear so much about recently. I hadn’t touched it for years. Despite my initial hesitation, I quickly got back in the saddle and came to appreciate its performance and safety features. GitHub Copilot also played a significant role, allowing me to focus on problem-solving rather than getting bogged down in syntax.</p><p>This year’s AoC was both challenging and enjoyable, breaking away from routine. I want to delve deeper into these reflections and see if they resonate with you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZaV86H2cUcDbSzq8" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Choosing Rust</h3><p>For this year&#39;s AoC I decided to use Rust. It had been over three years since I last used the language, but the challenge felt like the perfect opportunity to revisit it. I’ve always appreciated Rust for its thoughtful design, and I was curious to see how it would perform for the algorithm-heavy problems AoC is known for.</p><p>One of my initial concerns was Rust’s reputation for having a steep learning curve. I used it before, so I didn’t need to learn the language from scratch, plus my prior experience with C++ gave me a head start. Concepts like ownership, move semantics, and constant objects were already well-known to me. Even the notorious lifetime annotations turned out to be less daunting than I had feared — I only needed them a few times, and the compiler’s error messages guided me through the process effectively.</p><p>I should note that the problems didn’t require overly complex solutions. A single file was sufficient and my largest file was under 400 lines. This allowed me to focus on the algorithms and less on managing complicated codebases or dependencies.</p><p>Looking back, using Rust for AoC 2024 turned out to be a solid choice.</p><h4>Rediscovering Rust’s Strengths</h4><p>I’ve always admired Rust’s design, but the AoC this year gave me a deeper appreciation for how thought-through the language is. One feature that caught me was its approach to numeric operations. Methods like add, checked_add, wrapping_add, and saturating_add forced me to think about the effect I really want to achieve and how the algorithm should behave on the data type boundaries, avoiding the too-common problems with number overflows or unexpected results. It is a bit artificial case in our day-to-day programming problems, but in AoC problems where I very often iterate on an array or grid until some end condition is met is the explicit specification of behavior useful. It came in handy a few times when I wrote buggy logic decrementing unsigned integers.</p><p>One area I was afraid of and where Rust didn’t actually get on my nerves was its lifetime annotations. Before starting AoC, I’d anticipated wrestling with lifetimes, expecting them to slow me down. Surprisingly, I only needed to use them a couple of times, and even then, the compiler’s guidance made it straightforward. The error messages didn’t just highlight the problem — they effectively showed me how to solve it and I just needed to copy-paste the compiler’s suggestions. It felt almost like cheating, but it reinforced how Rust compiler errors can be helpful. The last 25 days gave me a new level of confidence in the language.</p><h4>Performance and Optimization</h4><p>Rust’s aggressive compiler optimizations and the use of SIMD instructions delivered consistently strong performance. Operations on arrays (what Rust refers to as vectors) were executed with efficiency, leveraging modern CPU capabilities without requiring any special effort from my side. On the contrary, my attempts to optimize certain algorithms manually did not always yield better results. For instance, on Day 9, I tried reducing the frequency of array modifications, assuming that fewer deletes inside the array would improve the overall speed. However, my optimizations ended up slowing the program down. Rust’s compiler was already generating highly efficient code for the original implementation utilizing techniques like loop unrolling and vectorization. This demonstrates how Rust allows you to write clear and straightforward code, while the compiler takes care of the complex task of optimizing performance.</p><h4>Challenges with Rust</h4><p>Of course, Rust isn’t perfect — no language is. There are a few things I wish were different. One minor frustration was the lack of implicit type conversions in situations where no precision would be lost. For example, converting a u8 to a u32 always required an explicit cast (as u32). I understand the reasoning behind this strictness—it enforces clarity and avoids ambiguity—but it feels like an unnecessary boilerplate. When the type changes, it is usually necessary to go through the code and change the casts everywhere. In competitive scenarios like Advent of Code, where every second can matter, even small interruptions like these add up (no that I would end within the first 100 even without it).</p><p>Another challenge was Rust’s ownership model, which made certain data structures almost impossible to implement. Doubly linked lists and trees, for instance, often require references pointing both ways, requiring unsafe blocks or elaborate workarounds to manage references correctly. On Day 16, I initially started with structures to represent my data in a graph, but I ran into difficulties when trying to reference parent nodes from children. Ultimately, I decided to rewrite the solution using vectors, which avoided the ownership issues entirely. Funnily, nowadays we call this “simplification” column-based approach or SoA (Structure of Arrays).</p><h3>Gen AI</h3><p>The rapid rise of large language models (LLMs) has changed how we approach competitions like Advent of Code. When I look at the leaderboard, it’s striking how quickly some participants submit their solutions — often within seconds of a problem being released. Solving these puzzles so fast, faster than I can even finish reading the description, clearly involves automation or LLM-based tools. The idea of a person solving problems that fast is just absurd.</p><p>But I don’t want to complain here, I’m not discouraged by this development. If anything, I see it as a natural evolution. I’m actually happy to see progress in development “agents,” which let me focus more on the core problem rather than getting pinned down in implementation details. I don’t feel threatened by these tools; instead, I see them as collaborators, enhancing productivity and letting me concentrate on the bigger picture.</p><p>There is one more thing — in contrast to the projects that we work on a day-to-day basis, the tasks in Advent of Code were still relatively short — a few dozen lines of code. In larger projects, that can span thousands or even millions of lines, the challenge shifts. It’s no longer about writing the code, but understanding the project, its structure, knowing where each functionality is, and why there are these wild constructs that are present in every project. This would require development agents to build an internal knowledge of an application’s architecture, structure, and organization, and all the nasty pieces that nobody wants to touch (the next project will be different, I swear). LLMs are not there yet, but I’m excited about the progress that is ahead of us.</p><h4>GitHub Copilot</h4><p>THE tool I used extensively — GitHub Copilot. Having been away from Rust for three years, I remembered the core concepts but already forgot the specific syntax — method names, iteration operations, or minor details of the language. Copilot helped bridge that gap effectively. It was not about blindly relying on the tool; instead, I treated it like a collaborative partner. I reviewed every suggestion it made, making sure that the code was correct, but also to understand what the code was doing. I consider this the “responsible” way how to use gen AI tools. This balance kept me in control of the process while using Copilot to fill in the blanks quickly.</p><p>I think we’ve shifted the boundary of what can “be done by machine” a bit further with Copilot and alike tools. It’s not just about generating code, but also about how well these tools integrate with your workflow. Copilot might produce a piece of code that’s tens of lines long in a single click, but for me, that’s only the first step. Typically, I’d generate code in a place where is the necessary context, then immediately refine it using my IDE’s refactoring tools (I prefer JetBrains IDE suite) — renaming variables for clarity, extracting methods, or restructuring the logic to better suit the problem at hand. This workflow takes full advantage of Copilot’s capabilities while ensuring the output remains clean and maintainable. I’ve found that generating code first and refactoring afterward is often more effective than letting Copilot generate the method directly.</p><p>By focusing on the problem’s broader structure and letting Copilot handle the repetitive or low-level implementation details, I could spend more time solving the actual challenges of Advent of Code. I enjoyed this kind of collaboration, feeling I had been pair programming with somebody who could also write boring, repetitive code without complaints.</p><h3>Does the university help?</h3><p>Reflecting on my Advent of Code experience, I’d say a university education can provide a noticeable edge, especially when solving puzzles that lean on mathematics or computer science fundamentals. For instance, modular algebra and its combination with prime numbers were helpful insights for Day 14’s puzzle. If you’ve encountered similar problems in a classroom setting, you’re likely to spot these patterns faster. That said, the puzzles are designed to be solvable even without a degree. A bit of trial and error, or brute force, can often lead to the same findings, although you may not formalize it or understand why it holds.</p><p>A solid understanding of algorithms and data structures also proved valuable. A fair share of solutions were built on top of Breadth-First Search or Dijkstra’s algorithm. While it’s entirely possible to reinvent these algorithms yourself, knowing them beforehand means you can jump straight to implementation. This isn’t just about saving time; I for example feel better when I know the path that leads me to my target, rather than wandering around. Of course, those who haven’t studied these topics have plenty of room to learn by doing — sometimes, you end up intuitively writing a well-known algorithm without realizing it.</p><p>And of course, we still have tools like GitHub Copilot that can generate these algorithms for you if you describe them clearly. It is just better if you know what was generated for you.</p><h3>Wrap it up</h3><p>Completing Advent of Code 2024 was a milestone for me. After years of trying without having time or dedication to finish, I completed all 25 days, driven by friendly competition with colleagues. Using Rust added to the challenge and reward. Despite not using it for years, tools like GitHub Copilot made the experience smoother than I expected.</p><p>This year brushed my algorithmic and mathematical knowledge while showing how far the gen AI tools have come. I’m excited about the role of such tools in development, helping programmers in their work.</p><p>In the end, I would like to thank Erik, the author of Advent of Code, for his time and dedication to this wonderful project. I want to thank the Reddit community for a bottomless stream of memes. hope you will help me save Christmas next year.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e1b7e5b0199" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qest/the-advent-of-code-2024-and-what-did-i-take-from-it-4e1b7e5b0199">The Advent of Code 2024 and what did I take from it</a> was originally published in <a href="https://medium.com/qest">Qest technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Power of Generative AI Models at AWS Cloud Day in Prague]]></title>
            <link>https://medium.com/qest/exploring-the-power-of-generative-ai-models-at-aws-cloud-day-in-prague-803fc6583a69?source=rss-ac7bf31ff80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/803fc6583a69</guid>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Patrik Valkovic]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 17:31:00 GMT</pubDate>
            <atom:updated>2023-10-30T17:31:00.742Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week, I had the pleasure of attending the AWS Cloud Day in Prague, and it was nothing short of amazing. The conference was an amazing opportunity to meet engineers from AWS and their partners, but also other bright minds in software engineering and Amazon Web Services. The talks were captivating, the people were inspiring, and the booths were brimming with the latest tech advancements from AWS and its partners like Snyk, Revolgy, and others, offering fascinating conversations and insights into the cutting-edge world of cloud computing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GukChasdWmi4GzKCdUK_2Q.jpeg" /></figure><p>One of the central themes that repeated throughout the event was the incredible potential of generative AI models and the many possibilities they unlock. Foundation models took the spotlight, dominating discussions and sessions, and reshaping how we approach AI development.</p><h3>The Power of Generative AI Models</h3><p>At the heart of the discussions were foundation models — large neural networks trained on enormous datasets. These models are changing the game in machine learning by serving as a foundational starting point for creating AI models. They’re incredibly powerful, understanding language and performing tasks like generating text, question answering, summarization, and more.</p><p>The foundation models showcased during the conference highlight the expansive capabilities these models offer. Their ability to understand natural language, generate text, images, and engage in meaningful dialogue marks a significant leap in AI capabilities.</p><h3>Introducing AWS Bedrock</h3><p>AWS Bedrock is a significant milestone. It’s a service offering an array of foundation models, not only from AWS, but also from other providers. The lineup includes models like Amazon TITAN for text generation, Jurassic for question answering, Claude, Llama 2 from Meta, and Stable Diffusion. Bedrock provides straightforward API access to these models for predictions and allows for fine-tuning, making it an invaluable resource for developers seeking to leverage these cutting-edge models.</p><p>And that brings us to another topic: fine-tuning. Fine-tuning offers developers a means to adapt and refine existing powerful foundation models. Whether it’s adjusting the entire model or just on a subset of layers, fine-tuning caters to customization for specialized tasks or domains. However, this process requires a substantial dataset and time for model refinement.</p><p>It’s crucial to note that the possibilities don’t end there — alongside fine-tuning, the event emphasized the use of Retrieval-Augmented Generation (RAG) as a means to further enhance AI capabilities. This method combines the strengths of retrieval-based and generative models, allowing to provide the model further context and thus improving the quality and relevance of generated text, especially in fields requiring specific domain knowledge like law, healthcare, or civil engineering.</p><h3>Applications Transforming the Landscape</h3><p>Generative AI models gave birth to applications that have changed how we interact with technology. From ChatGPT and GitHub Copilot to DALL-E 2 for image generation and AWS CodeWhisperer, these tools are reshaping the way we approach problem-solving and even programming. Important to note here is that AWS CodeWhisperer is built on top of these foundation models, so the possibilities are really limitless.</p><h3>The Power of AWS SageMaker</h3><p>The work is not always about taking the foundation model and using it directly. Sometimes, you want to fine-tune it for your specific needs, or sometimes you want to train your own model. AWS SageMaker emerged as the go-to tool for exactly that. SageMaker is a fully managed service tailored for machine learning development. What sets it apart is its user-friendly approach for data scientists and developers alike. With SageMaker, the error-prone tasks of building, training, and deploying machine learning models are streamlined, allowing users to focus on business innovation rather than the complexities of infrastructure management. The SageMaker simplifies the deployment process, allowing models to be launched into secure and scalable environments with just a few clicks via SageMaker Studio or the console.</p><p>SageMaker provides an array of optimized machine-learning algorithms and models designed to efficiently handle the majority of problems you may want to solve. These models are in SageMaker JumpStart just at your fingertips. The merit of SageMaker extends to its adaptability and customization features. Not only does it facilitate the training of models, but it also evaluates their performance and, when needed, deploys them seamlessly. You may use it also for initial data analysis, data cleaning, and feature engineering and transformation by adopting the SageMaker Data Wrangler tool.</p><p>The great thing is that it doesn’t confine users within its boundaries. The service offers the freedom to export transformations and code running behind the graphical user interface into Python or Jupyter scripts. This allows developers to integrate their work into their preferred environments and workflows, thus offering the best of both worlds — a powerful, integrated platform that’s also versatile and adaptable to individual needs.</p><h3>Specialized Hardware for AI Models</h3><p>AWS isn’t just stopping at models; they’re investing in specialized hardware that will make running these colossal models more cost-effective, efficient, and sustainable. The AWS-developed AI accelerator chips AWS Inferentia and AWS Trainium give substantial performance gain over the comparable EC2 GPU-based instance, while still being cheaper. The accelerators are promised to handle 100B+ parameter models with ease.</p><h3>The Unfolding Future</h3><p>WS Cloud Day was a glimpse into the promising world where AI will help us achieve more. Don’t get me wrong, the conference wasn’t just about AI, but it was still a recurrent topic.</p><p>I left the conference with my head full of ideas and anticipation for what lies ahead in the world of AI. I can’t wait to experiment with some of the models and I hope this text will convince you to give it a try as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=803fc6583a69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qest/exploring-the-power-of-generative-ai-models-at-aws-cloud-day-in-prague-803fc6583a69">Exploring the Power of Generative AI Models at AWS Cloud Day in Prague</a> was originally published in <a href="https://medium.com/qest">Qest technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless GraphQL Subscriptions on Amazon Web Services]]></title>
            <link>https://medium.com/qest/serverless-graphql-subscriptions-on-amazon-web-services-54fbbc0ed7ae?source=rss-ac7bf31ff80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/54fbbc0ed7ae</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[graphql-subscriptions]]></category>
            <dc:creator><![CDATA[Patrik Valkovic]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 09:40:10 GMT</pubDate>
            <atom:updated>2023-03-27T09:40:10.899Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TL;DR I used API Gateway, Lambda, and DynamoDB. DynamoDB is necessary to store data between subscription creation and its invocation. There are no popular ready-to-use libraries, so I needed to fallback to graphql package and manage it by hand. The complete source code is at my <a href="https://github.com/PatrikValkovic/ServerlessGraphQL">GitHub</a>.</blockquote><p>In recent years, GraphQL has gained significant popularity as a powerful alternative to traditional REST APIs due to its ability to provide precise data requirements and reduce overfetching of data. One of the key features of GraphQL is its ability to support real-time data updates through subscriptions. In this article, we will explore how to implement GraphQL subscriptions using AWS Lambda, AWS API Gateway, and DynamoDB. This combination of services enables developers to build scalable, real-time applications without the need for complex server infrastructure. We will walk through the step-by-step process of setting up a GraphQL subscription service on AWS and demonstrate how it can be used to create a simple real-time chat application.</p><p>The technologies we are going to use are:</p><ul><li><strong>API Gateway</strong> allows developers to easily create, deploy, and manage APIs at scale with features such as caching, security, and easy integration with other AWS services and third-party services.</li><li><strong>AWS Lambda</strong> is a serverless compute service that runs code without provisioning or managing servers, scales automatically based on incoming traffic, and supports a variety of programming languages and event sources. One possible event source is request to API Gateway.</li><li><strong>AWS DynamoDB</strong> is a fully managed NoSQL database service that provides low-latency, high-throughput data access with seamless scalability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K02K9UKEB33qUmLa" /><figcaption><a href="https://qeetup.qest.cz/">Qeetup #14</a></figcaption></figure><h3><strong>Queries and mutations</strong></h3><p>Let&#39;s start by implementing mutation and queries. It will be implemented by our first Lambda function, which is triggered by REST API Gateway.</p><p>We cannot use the Apollo server library since AWS Lambda only accepts event objects, not native Node request. Even though there are libraries that can bridge this gap, I will be using functions from the <a href="https://www.npmjs.com/package/graphql">graphql</a> package because it will be beneficial during subscription implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89f1c4d5f825e4a7bae13c3f7c0c948a/href">https://medium.com/media/89f1c4d5f825e4a7bae13c3f7c0c948a/href</a></iframe><p>Firstly, the code imports necessary functions from the GraphQL library and a schema file, which defines the structure of the data graphql that can be queried.</p><p>The handler function receives an APIGatewayEvent object as input, which contains information about the incoming HTTP request. Notice that the handler receives the body as plain text, so the handler needs to parse it first into JSON on line 8.</p><p>The body is then parsed again using the GraphQL parse function to convert it into an abstract syntax tree representation of the query. The parsed query is then validated against the schema to ensure it conforms to the specified data structure. If the query is valid, the execute function is called with the parsed query, user-provided variables, and context. The result of the query execution is returned as an HTTP response.</p><p>That was quite easy! Now we may do the same for subscriptions.</p><h3>WebSocket API Gateway</h3><p>Unlike a REST API, WebSockets require an open connection between the client and server, which is inherently stateful. However, AWS Lambda functions are stateless, meaning they don’t maintain any state between invocations. To solve this problem, AWS WebSocket API Gateway is used to keep the connection open and trigger a Lambda function for each message received, allowing for real-time, two-way communication while maintaining the benefits of stateless processing in Lambda.</p><p>Connections are identified by a ConnectionId property, which Lambda receives with each invocation. It can use it to uniquely identify the connection and, most importantly, send messages back to the client.</p><h4>WebSocket handshake</h4><p>The first thing we need to deal with is WebSocket handshake. It is a form of negotiation between the browser and server to agree on connection properties like subprotocol, extension, and more.</p><p>Because we use GraphQL, we will use the <a href="https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md">graphql-transport-ws</a> subprotocol (more about that later). To tell the browser we use that subprotocol, we need to return the following headers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0042d1a3acee0e258f9709d853fd09cc/href">https://medium.com/media/0042d1a3acee0e258f9709d853fd09cc/href</a></iframe><p>Notice that Sec-Websocket-Accept header, that is necessary for establishing the connection. It&#39;s form and the magic string “258EAFA5-E914–47DA-95CA-C5AB0DC85B11” is necessary to comfort WebSocket specification.</p><p>After the browser establishes a connection to the API Gateway, we may start sending subscriptions.</p><h4>Subprotocol</h4><p>I choose <a href="https://www.npmjs.com/package/graphql-ws">graphql-ws</a>, which uses <a href="https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md">graphql-transport-ws</a> subprotocol. Do not confuse the subprotocol with now deprecated library <a href="https://github.com/apollographql/subscriptions-transport-ws">subscriptions-transport-ws</a>, which uses <em>graphql-ws</em> subprotocol (bit confusing, I know).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQrnpcito8Zsc04riybnmA.png" /></figure><p>The protocol starts with the ConnectionInit message, which indicates that the client wants to establish a connection on the socket. It also carries connection properties like user ID. After receiving the ConnectionInit message and after successful authorization, the server sends the ConnectionAck message back to the client.</p><p>The client can then request subscription operations by sending the Subscribe message, which provides a unique ID field to correlate answers from the server to specific subscription. Once some event triggers a subscription, the server sends the execution result in the Next message.</p><p>After some time, the user or server can send a Complete message to close the subscription.</p><h3>Subscription handler</h3><p>Now we may implement Lambda function that will handle the subprotocol messages. We need to implement all the messages above, but the most important is the subscription.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1985f947c1beab4d8dfdc1572700287/href">https://medium.com/media/a1985f947c1beab4d8dfdc1572700287/href</a></iframe><p>As with query, we will parse the API Gateway event, followed by parsing user request into GraphQL syntax tree, validation, and executing the subscription on the schema.</p><h3>Architecture</h3><p>We are still missing one thing from the working solution — we can’t send messages back to the user. Before we get to the implementation, let’s look at the architecture of the complete solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*nlzjZ2N5rXv77GO8U_m8RA.png" /></figure><p>Publish function is Lambda, which will send messages back to the user. As you may see, it is completely disconnected from the subscription function, which processes messages from the users. That has few implications, but most importantly all the information that the publish function needs must flow through the DynamoDB.</p><p>And how AWS knows when to invoke that function? We will use AWS Simple Queue Service, which is managed message-broker service. Every time we publish a new event to the queue, it will trigger the publish function that will in turn send resolved values back to our users.</p><h4>DynamoDB record</h4><p>So what information needs to be stored in the database?</p><ul><li>Connection ID, so that we know to which connection to send subscription to.</li><li>Subscription ID, that identifies user subscription for which the response message will be for.</li><li>Routing key or topic key — this is a standard string that identifies the type of event to which we react. There may be multiple types of subscriptions for a single event (for example new message event may invoke subscription newMessage, but as well numberOfUnreadMessages). This is similar to the standard way we register for events in GraphQL.</li><li>GraphQL query — because each subscription may have different fields to resolve, we also need to rebuild the original query user sent us.</li><li>GraphQL variables — serialized variables that the user sends with the query. Similarly to the field above, we need to reconstruct the original query in a new lambda function, and to do that we need all the information user sent us.</li><li>TTL — this is more a safeguard than a necessity. WebSocket API Gateway keeps connections alive for 2 hours max, so we may safely remove old records after that period.</li><li>Pseudo-serialized context is the most interesting field. As mentioned, the publish function needs to know how to build the original query. If the application has some user-specific information in context (like user ID, role, etc.) this needs to be stored in the database as well, so we may recreate it. This doesn’t apply for services, database connection, etc. because we can recreate it in the publish lambda directly.</li></ul><h3>Answering to subscriptions</h3><p>The publish function implementation is then straightforward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c928bfc7f9746ced7ac4d66836e8b540/href">https://medium.com/media/c928bfc7f9746ced7ac4d66836e8b540/href</a></iframe><p>The publish function first uses the getByRoutingKey function to retrieve a list of subscriptions that match the routing key from DynamoDB.</p><p>For each subscription, the function parses the subscription body and invokes the subscription operation, along with user variables and context. The operations return an async iterator, from which we get the resolved value and send it back to the user.</p><h3>Writing to DynamoDB</h3><p>I concealed from you one piece of information — how to write to DynamoDB. The GraphQL subscription across the libraries has two operations — subscribe and resolve. For the nexus <a href="https://www.npmjs.com/package/nexus">library</a>, the subscription code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830ca12abdd630c1dbb1a7cfbb9040a5/href">https://medium.com/media/830ca12abdd630c1dbb1a7cfbb9040a5/href</a></iframe><p>The subscribe operation returns an async iterator — we may use that and inject there our own implementation. What’s more, we will even have two implementations.</p><ol><li>One for subscription lambda function — it will just write all the necessary data into the DynamoDB and returns an empty iterator with no records.</li><li>The second one is for publish function. We feed it with the DynamoDB record and event that invoked the function. It will emit just one object and then ends.</li></ol><p>This way, the GraphQL implementation can be completely unaware of the Lambda function within its running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BzRJ-9guyAz8Xu9J" /></figure><h3>Conclusion</h3><p>We successfully implemented GraphQL subscriptions using a purely serverless approach. Because there are no good libraries prepared for this task, we implemented it from scratch using the <em>graphql</em> package.</p><p>Many details have been omitted to make this article easy to understand. Complete source codes with ready-to-use deployment scripts using CDK is at my GitHub <a href="https://github.com/PatrikValkovic/ServerlessGraphQL">https://github.com/PatrikValkovic/ServerlessGraphQL</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54fbbc0ed7ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qest/serverless-graphql-subscriptions-on-amazon-web-services-54fbbc0ed7ae">Serverless GraphQL Subscriptions on Amazon Web Services</a> was originally published in <a href="https://medium.com/qest">Qest technologies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>