<?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 Tesar Wijaya on Medium]]></title>
        <description><![CDATA[Stories by Tesar Wijaya on Medium]]></description>
        <link>https://medium.com/@tesarwijaya?source=rss-97b96b33b48b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DtQRcnZnhjvVzwEgcA5CjQ@2x.jpeg</url>
            <title>Stories by Tesar Wijaya on Medium</title>
            <link>https://medium.com/@tesarwijaya?source=rss-97b96b33b48b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:38:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tesarwijaya/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[Setup Change Data Capture With Maxwell and Docker]]></title>
            <link>https://medium.com/@tesarwijaya/setup-change-capture-data-with-maxwell-and-docker-cc936dbd77d0?source=rss-97b96b33b48b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc936dbd77d0</guid>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Tesar Wijaya]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 10:09:42 GMT</pubDate>
            <atom:updated>2025-02-17T12:41:28.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jm6pRnz0ZDFj6Ue-" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Change Data Capture (CDC) is a process that detects and tracks changes in a database in real time. Instead of periodically querying for updates, CDC listens for <strong>INSERT, UPDATE, and DELETE</strong> operations and streams them to external systems, and then the external systems will do something based on the information. This is especially useful for:</p><ul><li><strong>Event-driven architectures</strong> — Triggering actions based on database changes.</li><li><strong>Data synchronization</strong> — Keeping multiple data stores in sync (e.g., MySQL → Elasticsearch).</li><li><strong>Real-time analytics</strong> — Streaming updates to a data warehouse or BI tool.</li></ul><h3>So, What is Maxwell?</h3><p>At their official documentation <a href="https://maxwells-daemon.io/">here</a>, they define it as a change data capture application that reads MySQL binlogs and writes data changes as JSON to Kafka, Kinesis, and other streaming platforms.</p><p>I found maxwell stands out for several reasons:</p><ol><li>Lightweight and Easy to Setup<br>You can run it in a single container with minimal setup.</li><li>Supports Multiple Outputs<br>Whether you’re using RabbitMQ, Kafka, Kinesis, Redis, or even HTTP webhooks, Maxwell can stream CDC events effortlessly.</li><li>No Database Schema Changes Required<br>Maxwell doesn’t modify your schema, making it non-intrusive.</li></ol><h3>Setup Docker Compose File</h3><p>We’ll use <strong>Docker Compose</strong> to set up our CDC. It’s a great tool for spinning up multiple services at once and simplifying commands by leveraging a YAML configuration file.</p><p>Now, in our project directory let’s create a new file called <strong>docker-compose.yml</strong> and add the following lines:</p><pre>services:<br>  mysql:<br>    image: mysql:8.0<br>    container_name: mysql<br>    environment:<br>      MYSQL_ROOT_PASSWORD: example-password<br>      MYSQL_DATABASE: example-db<br>      MYSQL_USER: example-user<br>      MYSQL_PASSWORD: example-password<br>    ports:<br>      - &quot;3306:3306&quot;<br>    volumes:<br>      - mysql-data:/var/lib/mysql<br>      - ./my.cnf:/etc/mysql/my.cnf<br><br>volumes:<br>  mysql-data:<br>    driver: local</pre><p>The provided code defines a service for running a MySQL database container. The container is named mysql and uses the mysql:8.0 image, also set several environment variables required for our MySQL service, ports and volume.</p><p>The volumes section sets up two volume mappings. The first one, mysql-data:/var/lib/mysql, makes sure MySQL data is stored persistently on the host machine, so it doesn’t get lost when the container is removed. This makes development smoother since we don’t have to start from scratch every time the container restarts.</p><p>The second mapping, ./my.cnf:/etc/mysql/my.cnf, is essential for our project because we need to configure MySQL with log-bin=mysql-bin, binlog_format=ROW, and binlog_row_image=FULL. These settings allow Maxwell to capture data changes from the MySQL binlog.</p><p>Now, let’s create the <strong>my.cnf</strong> configuration file:</p><pre>[mysqld]<br>server-id=1<br>log-bin=mysql-bin<br>binlog_format=ROW<br>binlog_row_image=FULL<br>binlog_expire_logs_seconds=604800<br>max-binlog-size=100M</pre><p>and then place them at root folder of our project.</p><p>It should be enough for now to run our MySQL service with command:</p><pre>docker-compose up -d --build</pre><p>Next, since Maxwell will be sending data changes to RabbitMQ, let’s add a RabbitMQ service to our docker-compose.yml file:</p><p>Simply add the following lines:</p><pre>rabbitmq:<br>    image: rabbitmq:3-management<br>    container_name: rabbitmq<br>    ports:<br>      - &quot;5672:5672&quot;<br>      - &quot;15672:15672&quot;<br>    environment:<br>      RABBITMQ_DEFAULT_USER: admin<br>      RABBITMQ_DEFAULT_PASS: admin</pre><p>Since the configuration is pretty straightforward, we don’t need to go into detail about the code itself. However, one key thing to note is that we’re exposing two ports to our local machine:</p><ul><li><strong>5672</strong> — Used by RabbitMQ clients to connect to the service.</li><li><strong>15672</strong> — Used to access the RabbitMQ admin dashboard.</li></ul><p>And then finally, the last part! Put this following code inside the services:</p><pre>maxwell:<br>    image: zendesk/maxwell:latest<br>    container_name: maxwell<br>    depends_on:<br>      - mysql<br>      - rabbitmq<br>    command: &gt;<br>      bin/maxwell<br>      --host=mysql<br>      --user=root<br>      --password=example-password<br>      --schema_database=maxwell<br>      --rabbitmq_host=rabbitmq<br>      --rabbitmq_port=5672<br>      --rabbitmq_user=admin<br>      --rabbitmq_pass=admin<br>      --rabbitmq_virtual_host=/<br>      --rabbitmq_exchange=maxwell<br>      --rabbitmq_exchange_durable=true<br>      --filter=include:example-db.*<br>      --producer=rabbitmq<br>      --log_level=debug</pre><p>The code above sets up a Maxwell service using the latest version of its image. We also define the depends_on list to ensure that Maxwell starts only after mysql and rabbitmq are up and running.</p><p>In the command section, make sure to double-check your MySQL and RabbitMQ credentials—Maxwell needs them to establish a proper connection.</p><p>Pay special attention to the MySQL user used by Maxwell; it must have SELECT, REPLICATION CLIENT, and REPLICATION permissions. Also, keep in mind that Maxwell <strong>does not capture data changes from tables in </strong><strong>schema_database</strong> since it treats them as internal tables and won’t publish their changes to the producer.</p><p>To avoid this limitation, I recommend using a specific database schema for Maxwell. The code above is set up to publish data changes <strong>only from tables in </strong>example-db, thanks to the filter<strong> </strong>option in the Maxwell command.</p><p>The complete docker compose file should be look like this:</p><pre>services:<br>  mysql:<br>    image: mysql:8.0<br>    container_name: mysql<br>    restart: always<br>    environment:<br>      MYSQL_ROOT_PASSWORD: example-password<br>      MYSQL_DATABASE: example-db<br>      MYSQL_USER: example-user<br>      MYSQL_PASSWORD: example-password<br>    ports:<br>      - &quot;3306:3306&quot;<br>    volumes:<br>      - mysql-data:/var/lib/mysql<br>      - ./my.cnf:/etc/mysql/my.cnf<br><br>  rabbitmq:<br>    image: rabbitmq:3-management<br>    container_name: rabbitmq<br>    ports:<br>      - &quot;5672:5672&quot;<br>      - &quot;15672:15672&quot;<br>    environment:<br>      RABBITMQ_DEFAULT_USER: admin<br>      RABBITMQ_DEFAULT_PASS: admin<br><br>  maxwell:<br>    image: zendesk/maxwell:latest<br>    container_name: maxwell<br>    depends_on:<br>      - mysql<br>      - rabbitmq<br>    ports:<br>      - &quot;8080:8080&quot;<br>    command: &gt;<br>      bin/maxwell<br>      --host=mysql<br>      --user=root<br>      --password=example-password<br>      --schema_database=maxwell<br>      --rabbitmq_host=rabbitmq<br>      --rabbitmq_port=5672<br>      --rabbitmq_user=admin<br>      --rabbitmq_pass=admin<br>      --rabbitmq_virtual_host=/<br>      --rabbitmq_exchange=maxwell<br>      --rabbitmq_exchange_durable=true<br>      --filter=include:example-db.order<br>      --producer=rabbitmq<br>      --log_level=debug<br><br>volumes:<br>  mysql-data:<br>    driver: local</pre><p>Run with command to see the result:</p><pre>docker-compose up -d --build</pre><p>You can verify if the container is running properly by using command docker ps and give following list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xA8BedUHQCMSjthTpI8Sw.png" /></figure><p>And that’s it! All you have to do now is create a consumer and do something with the data changes!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc936dbd77d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Microservices Aren’t Always the Best Choice for Small Teams]]></title>
            <link>https://medium.com/@tesarwijaya/why-microservices-arent-always-the-best-choice-for-small-teams-d8678e2df11f?source=rss-97b96b33b48b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8678e2df11f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Tesar Wijaya]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 14:36:35 GMT</pubDate>
            <atom:updated>2025-01-27T14:36:35.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pi-di3nrbeRdhmEH" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Microservices have been hailed as the goto solution for building scalable, flexible systems. But in my experience with small teams, they often cause more problems than they solve. Instead of accelerating development, their complexity can overwhelm smaller teams, creating bottlenecks and complicating processes. This were my takes on as someone who were working with microservices both as large and small teams:</p><h3>When Services Are Too Small</h3><p>One of the most common mistakes I’ve seen is breaking services down too much. While the idea of single-responsibility services sounds great on paper, it often leads to what I call “nano-services” — tiny services that do just one specific thing. At first, this might seem manageable, but as these nano-services grow, small teams struggle to keep up with maintenance.</p><p>For a small team, it’s better to focus on cohesive functionality and keep the number of service down. Keep services cohesive by focusing on their core functionality. Meaningful services should encapsulate a distinct and valuable business capability, avoiding unnecessary fragmentation. Splitting services should only occur when there’s a valid, business-driven reason, such as scalability or ownership needs. Wait until there’s a valid, business-driven reason to separate a service.</p><h3>Service Ownership</h3><p>In larger companies with big teams, service ownership isn’t usually a problem. But for smaller teams, it can quickly become an overwhelming burden — especially when services are broken down into overly granular pieces. A single team often ends up responsible for too many services.</p><p>From my experience, there were times when a squad of just two backend engineers managed over five backend services. With such limited resources, they not only had to develop new features for each service but also monitor, debug, handle deployments, and resolve service-specific issues. I remember one particular period when our team was juggling multiple urgent feature requests alongside production issues for several services. The constant context-switching and time constraint left us with no bandwidth to explore new ideas or optimize existing processes.</p><h3>Deployment and Development Are Anything But Simple</h3><p>Microservices are often touted as the key to faster deployments and agile development cycles. But for small teams, the reality is far from ideal. Before enabling agile workflows, each service needs its own CI/CD pipeline, infrastructure, and monitoring. Setting up and maintaining this infrastructure requires significant effort, and ensuring quality across all services becomes new challenge.</p><p>What might have been a straightforward deployment process with a monolith turns into a sprawling web of dependencies and configurations. I recall a time when I had to make changes across three services for a single feature. Since my squad owned all three, I had to create three separate pull requests, which then needed individually reviewed by my peers. Once merged and tested, I still faced the challenge of deploying all three services, ensuring dependencies were intact, and carefully planning the rollout to avoid breaking production. This process is unnecessarily time-consuming and complicates development. It shall be easier and simpler if we just use one service instead.</p><h3>Too Many Repositories to Manage</h3><p>One common pattern with microservices is that each service has its own repository. With each service living in its own repository, managing code quality and consistency becomes harder. For small teams, maintaining standards across dozens of repositories can feel unmanageable.</p><p>Code reviews take longer, shared libraries often become fragmented, and best practices can fall by the wayside. Consolidating related services into a monorepo might ease some of this pain, but it also requires governance and tooling — both of which add to the team’s workload.</p><h3>Conclusion</h3><p>Microservices are powerful, but they’re not a one-size-fits-all solution. For small teams, the added complexity, coordination, and maintenance often outweigh the benefits.</p><p>In many cases, a modular monolith or even a backend-for-frontend (BFF) pattern might be a better option for smaller teams. These approaches keep things simple while still allowing for future scalability.</p><p>What has your experience with microservices been like? If you’ve faced similar challenges — or found ways to overcome them — let me know in the comments. I’d love to hear your thoughts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8678e2df11f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why gRPC Is Hard to Implement]]></title>
            <link>https://medium.com/@tesarwijaya/why-grpc-is-hard-to-implement-0f4af3cdfe46?source=rss-97b96b33b48b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f4af3cdfe46</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Tesar Wijaya]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 13:56:54 GMT</pubDate>
            <atom:updated>2024-11-24T13:56:54.923Z</atom:updated>
            <content:encoded><![CDATA[<p>Throughout my career, I’ve worked at three different companies with the idea of migrating internal services to gRPC. The appeal is obvious: gRPC offers faster communication, lower latency, and native support for bi-directional streaming, making it an enticing upgrade over REST APIs for internal service communication. Yet, despite its advantages, I’ve never seen a complete migration succeed.</p><p>Why? If gRPC is technically superior for internal service communication, what’s holding us back? In my experience, the challenges are less about gRPC itself and more about the broader implications of adopting it across teams and systems. Let’s unpack some of the key hurdles.</p><h4>1. Not Everyone Is Familiar with RPC</h4><p>One of the first roadblocks is familiarity. While REST is widely understood and its principles are second nature for most engineers, Remote Procedure Call (RPC) is different.</p><p>The gRPC framework, built on HTTP/2 and Protocol Buffers (Protobuf), requires engineers to think differently about how services communicate and develop features on top of it. For teams that haven’t worked with RPC before, there’s a learning curve. Without proper onboarding and documentation, gRPC is only a blocker for engineer to move fast.</p><h4>2. Protobuf Can Be Hard to Maintain</h4><p>gRPC uses Protobuf as its interface definition language, which is powerful. But, updating Protobuf definitions can be a tedious, especially in larger system with multiple teams involved. Every update needs a careful coordination to avoid breaking changes.</p><h4>3. Protobuf Makes Client and Server Tightly Coupled</h4><p>With gRPC in order for a client and a server be able to communicate properly, the Protobuf definitions between them need to be in sync. This means we cannot deploy the client and server independently anymore, especially when there are changes to the Protobuf definitions. Moreover, the “client” in this case isn’t limited to the frontend or user-facing components — it also includes other services connected to the server. So we need to put extra effort for coordination between teams to makes the deployment process run without issues.</p><h4>4. Load Balancing Limitations</h4><p>In REST architectures, load balancing often happens at Layer 4 (transport layer), which is simpler and works well with stateless HTTP. gRPC, however, relies on Layer 7 (application layer) load balancing due to its use of HTTP/2 multiplexing.</p><p>This dependency introduces additional complexity. Teams need to invest more in configuring load balancing strategy manually, which can delay adoption.</p><h4>5. Lack of Commitment Across Departments</h4><p>Finally, and perhaps most importantly, successful migration to gRPC requires buy-in from every department involved in service development and operation.</p><p>Without cross-team alignment, migration efforts tend to stall. Some teams might continue building on top of REST APIs while others experiment with gRPC, resulting in a fragmented system that adds more overhead than benefits. Migration isn’t just a technical decision — it’s an organizational commitment, and securing that commitment can be the hardest part.</p><h4>Conclusion</h4><p>There’s no doubt that gRPC has the potential to massively improve internal service communication, but it’s not a silver bullet. Its advantages come with a set of challenges that can only be overcome through proper planning and collaboration across teams.</p><p>In my experience, the real hurdles to adopting gRPC aren’t technical — they’re cultural and organizational. Until those challenges are addressed, gRPC migrations will likely remain a daunting task for most organizations.</p><p>Have you tried adopting gRPC in your organization? I’d love to hear about your experiences and how your team tackled (or struggled with) these challenges!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f4af3cdfe46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Makes a Great Unit Test?]]></title>
            <link>https://medium.com/@tesarwijaya/what-makes-a-great-unit-test-019871c0f8d7?source=rss-97b96b33b48b------2</link>
            <guid isPermaLink="false">https://medium.com/p/019871c0f8d7</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tesar Wijaya]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 12:12:41 GMT</pubDate>
            <atom:updated>2024-11-16T12:12:41.128Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit testing is a crucial part of software development, helping ensure individual components work as expected. But what separates a great unit test from just an average one? Here are a few things I keep in mind:</p><h4><strong>Focus on Business Logic and Requirements</strong></h4><p>A solid unit test should cover all the key business logic and requirements, including edge cases. The goal is to make sure the system behaves correctly under every scenario it’s likely to encounter. Covering these aspects early helps prevent bugs and keeps things running smoothly.</p><h4><strong>Don’t Chase Coverage Metrics Alone</strong></h4><p>While high code coverage can look good on paper, it doesn’t always mean the tests are useful. Great tests focus on checking the logic thoroughly rather than just hitting a percentage goal. Quality over quantity is the way to go here.</p><h4><strong>Write for Humans First</strong></h4><p>Remember, your tests aren’t just for machines — they’re for your team, too. Write tests that are easy for other developers to understand at a glance. Use descriptive names, straightforward logic, and clear comments where needed. A test that’s hard to follow is less useful, no matter how thorough it is.</p><h4><strong>Keep It Clear and Organized</strong></h4><p>Unit tests should be easy to read and navigate. Anyone on the team should be able to look at a test and immediately understand what it’s doing. Simple naming, clear structure, and avoiding unnecessary complexity make a huge difference.</p><h4><strong>Double as Documentation</strong></h4><p>Think of unit tests as a form of live documentation. They show how the system is supposed to behave and provide examples of expected inputs and outputs. This can reduce the need for separate documentation and make the code easier for others to pick up. Unit tests should also be your partners on the journey. This means that every time you make changes — whether due to updated requirements or fixing bugs — you should write and document these changes in the unit tests.</p><p>In short, great unit tests are thorough, meaningful, and easy to work with. Focus on these principles, and you’ll build tests that not only catch issues but also make life easier for the whole team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=019871c0f8d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending and receiving channel between goroutines in golang part 2]]></title>
            <link>https://medium.com/@tesarwijaya/sending-and-receiving-channel-between-goroutines-in-golang-part-2-28a6daf2a6ef?source=rss-97b96b33b48b------2</link>
            <guid isPermaLink="false">https://medium.com/p/28a6daf2a6ef</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Tesar Wijaya]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 14:56:18 GMT</pubDate>
            <atom:updated>2023-03-25T14:56:18.691Z</atom:updated>
            <content:encoded><![CDATA[<p>Building on our previous post where we discussed the basics of sending and receiving channels in Go <a href="https://medium.com/@tesarwijaya/sending-and-receiving-channel-between-goroutines-in-golang-part-1-9269eaab19c3">here</a>, in this post we will dive deeper into the topic of channels and explore more advanced techniques. We will discuss how to use the select statement to receive from multiple channels simultaneously, allowing goroutines to wait for messages from different sources. Additionally, we will cover how to receive from multiple channels using a for loop, and discuss best practices for working with channels in Go.</p><p>In Go, the select statement provides a way to receive messages from multiple channels simultaneously. It allows a goroutine to wait on multiple channels until one or more of them have data available to be received.</p><p>The select statement works by evaluating a list of cases, each of which represents a channel operation that the goroutine is waiting to perform. A case can be a send operation, a receive operation, or a default case that is executed if no other case is ready to be executed. The select statement will block until at least one of the cases is ready to be executed.</p><p>Here’s an example code snippet that demonstrates how to use the select statement to receive from multiple channels:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    ch1 := make(chan string)<br>    ch2 := make(chan string)<br><br>    go func() {<br>        time.Sleep(1 * time.Second)<br>        ch1 &lt;- &quot;Message from channel 1&quot;<br>    }()<br><br>    go func() {<br>        time.Sleep(2 * time.Second)<br>        ch2 &lt;- &quot;Message from channel 2&quot;<br>    }()<br><br>    for i := 0; i &lt; 2; i++ {<br>        select {<br>        case msg1 := &lt;-ch1:<br>            fmt.Println(&quot;Received message from channel 1:&quot;, msg1)<br>        case msg2 := &lt;-ch2:<br>            fmt.Println(&quot;Received message from channel 2:&quot;, msg2)<br>        }<br>    }<br>}</pre><p>In this example, we create two channels, ch1 and ch2, and start two goroutines that send messages on these channels after a certain amount of time. We then use the select statement to receive messages from both channels. Inside a for loop, we use two cases to listen to both channels simultaneously. When a message is received on either channel, the corresponding case will be executed and the message will be printed to the console.</p><p>By using the select statement, we can wait on multiple channels simultaneously and receive messages from them as soon as they become available. This makes it easy to coordinate the activities of multiple goroutines and enables us to write highly concurrent and efficient programs in Go.</p><p>The technique of using the select statement to receive from multiple channels is a powerful tool that can be used to solve real-world problems in a concurrent and efficient manner. For example, let’s consider the case where we want to save an image to a cloud storage bucket and then save a backup of the image to another bucket. We also want to write metadata about the image to a database.</p><p>To accomplish this task concurrently, we can create three separate goroutines, one for each task. Each goroutine can use a channel to communicate with the main goroutine, which is responsible for triggering the start of the process. The main goroutine can use the select statement to wait for each of the three goroutines to complete their task before moving on to the next step in the process.</p><p>The goroutine responsible for uploading the image to the first bucket can send a message on its channel when it’s done. Similarly, the goroutine responsible for uploading the backup image to the second bucket and the goroutine responsible for writing metadata to the database can also send messages on their respective channels when they’re done. The main goroutine can use the select statement to wait for all three channels to receive messages, indicating that all three tasks have been completed.</p><p>By using this technique, we can perform all three tasks concurrently and efficiently, without blocking the main goroutine. This allows us to scale our application and handle multiple requests simultaneously, making it a powerful tool for solving real-world problems.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    imageChannel := make(chan string)<br>    backupChannel := make(chan string)<br>    databaseChannel := make(chan string)<br><br>    // Start the goroutines<br>    go uploadImageToBucket(imageChannel)<br>    go uploadBackupToBucket(backupChannel)<br>    go writeToDatabase(databaseChannel)<br><br>    // Wait for all three channels to receive messages<br>    for i := 0; i &lt; 3; i++ {<br>        select {<br>        case msg := &lt;-imageChannel:<br>            fmt.Println(msg)<br>        case msg := &lt;-backupChannel:<br>            fmt.Println(msg)<br>        case msg := &lt;-databaseChannel:<br>            fmt.Println(msg)<br>        }<br>    }<br>}<br><br>func uploadImageToBucket(c chan string) {<br>    fmt.Println(&quot;Uploading image to bucket...&quot;)<br>    time.Sleep(2 * time.Second) // Simulate upload process<br>    c &lt;- &quot;Image uploaded to bucket&quot;<br>}<br><br>func uploadBackupToBucket(c chan string) {<br>    fmt.Println(&quot;Uploading backup image to bucket...&quot;)<br>    time.Sleep(2 * time.Second) // Simulate upload process<br>    c &lt;- &quot;Backup image uploaded to bucket&quot;<br>}<br><br>func writeToDatabase(c chan string) {<br>    fmt.Println(&quot;Writing metadata to database...&quot;)<br>    time.Sleep(2 * time.Second) // Simulate write process<br>    c &lt;- &quot;Metadata written to database&quot;<br>}</pre><p>In this example, we have three channels, one for each task. We start three goroutines, each responsible for completing one of the tasks. The main function waits for all three channels to receive a message using the select statement. Once all three tasks are completed, the program prints out the message received from each channel.</p><p>Note that we’re using the time.Sleep function to simulate the upload and write processes. In a real-world scenario, you would replace these with the actual functions to perform the uploads and writes.</p><p>However, the requirement has now changed. We want to ensure that the image is uploaded successfully before we save it to the backup server and write its metadata to the database. We can accomplish this by modifying the code:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    imageChannel := make(chan string)<br>    backupChannel := make(chan string)<br>    databaseChannel := make(chan string)<br><br>    // Start the goroutines<br>    go uploadImageToBucket(imageChannel)<br>    for msg := range imageChannel {<br>        fmt.Println(msg)<br>        go uploadBackupToBucket(backupChannel)<br>        go writeToDatabase(databaseChannel)<br>        break // Exit the loop after the first message is received<br>    }<br><br>    // Wait for all three channels to receive messages<br>    for i := 0; i &lt; 2; i++ { // Wait for backup and database channels only<br>        select {<br>        case msg := &lt;-backupChannel:<br>            fmt.Println(msg)<br>        case msg := &lt;-databaseChannel:<br>            fmt.Println(msg)<br>        }<br>    }<br>}<br><br>func uploadImageToBucket(c chan string) {<br>    fmt.Println(&quot;Uploading image to bucket...&quot;)<br>    time.Sleep(2 * time.Second) // Simulate upload process<br>    c &lt;- &quot;Image uploaded to bucket&quot;<br>}<br><br>func uploadBackupToBucket(c chan string) {<br>    fmt.Println(&quot;Uploading backup image to bucket...&quot;)<br>    time.Sleep(2 * time.Second) // Simulate upload process<br>    c &lt;- &quot;Backup image uploaded to bucket&quot;<br>}<br><br>func writeToDatabase(c chan string) {<br>    fmt.Println(&quot;Writing metadata to database...&quot;)<br>    time.Sleep(2 * time.Second) // Simulate write process<br>    c &lt;- &quot;Metadata written to database&quot;<br>}</pre><p>In this modified version, we wait for the image to be uploaded to the bucket before starting the backup upload and writing metadata to the database. We use a for loop to wait for the first message from the imageChannel. Once we receive the message, we start the backup and database goroutines and break out of the loop.</p><p>Note that we’re using a for loop to wait for the backup and database channels to receive messages instead of waiting for all three channels as we did in the previous example. This is because we&#39;re only interested in waiting for the backup and database tasks to complete once the image is uploaded.</p><p>In conclusion, using channels and the select statement in Go can greatly simplify concurrent programming and coordination between goroutines. By passing channels as arguments to goroutines and using them to communicate, we can create powerful and efficient concurrent systems. In the next post, we will continue exploring sending and receiving channels in Go, specifically how to receive from multiple channels by utilizing the select statement, as well as how to handle errors when one of our goroutines returns an error.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28a6daf2a6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending and receiving channel between goroutines in golang part 1]]></title>
            <link>https://medium.com/@tesarwijaya/sending-and-receiving-channel-between-goroutines-in-golang-part-1-9269eaab19c3?source=rss-97b96b33b48b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9269eaab19c3</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Tesar Wijaya]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 07:27:34 GMT</pubDate>
            <atom:updated>2023-03-23T07:28:25.305Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrency is a powerful feature of the Go, and channels are a key tool for coordinating activities between goroutines. While much attention is given to sending channels between goroutines, it’s equally important to understand how to receive channels in a safe and effective manner.</p><p>In Go, channels are a way to communicate and synchronize data between goroutines. One of the key features of channels is that they can be passed as arguments to goroutines, allowing multiple goroutines to communicate with each other.</p><p>To pass a channel as an argument to a goroutine, you simply include it as a parameter when starting the goroutine using the go keyword. Here&#39;s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func worker(ch chan string) {<br>    msg := &lt;-ch<br>    fmt.Println(&quot;Received message:&quot;, msg)<br>}<br><br>func main() {<br>    ch := make(chan string)<br>    go worker(ch)<br>    ch &lt;- &quot;Hello, World!&quot;<br>}</pre><p>In this example, we have a worker function that takes a channel of type string as an argument. Inside the worker function, we use the &lt;- operator to receive a message from the channel ch and assign it to the variable msg. We then print the received message to the console.</p><p>In main, we create a channel ch and pass it as an argument to the worker function by calling it in a new goroutine using the go keyword. We then send the string &quot;Hello, World!&quot; on the channel ch using the &lt;- operator.</p><p>By passing the channel ch as an argument to the worker function, we enable it to receive messages from the channel and perform some action on them. In this example, the worker function simply prints the received message to the console.</p><p>This example demonstrates how channels can be used to allow communication and synchronization between different parts of a program. By passing the channel as an argument to the worker function and using the &lt;- operator to receive messages from it, we enable the worker goroutine to receive and process messages sent by other parts of the program.</p><p>And that’s it! we already learn how to sending and receiving channel in Golang. We have not discussing about channel ownership, closing channel, how to receiving from multiple channels also best practices pattern for using it. We will discussing it in the next part!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9269eaab19c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>