Table of Contents
Pipeline Concurrency Pattern in Go: A Comprehensive Visual Guide
Souvik Kar Mahapatra ・ Dec 20 '24
Understanding and visualizing Goroutines and Channels in Golang
Home Backend Development Golang Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide

Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide

Jan 07, 2025 pm 10:24 PM

⚠️ How to go about this series?

1. Run Every Example: Don't just read the code. Type it out, run it, and observe the behavior.
2. Experiment and Break Things: Remove sleeps and see what happens, change channel buffer sizes, modify goroutine counts.
Breaking things teaches you how they work
3. Reason About Behavior: Before running modified code, try predicting the outcome. When you see unexpected behavior, pause and think why. Challenge the explanations.
4. Build Mental Models: Each visualization represents a concept. Try drawing your own diagrams for modified code.

Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide

In our previous post, we explored the Pipeline concurrency pattern, the building blocks of Fan-In & Fan-Out concurrency patterns. You can give it a read here:

Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide

Pipeline Concurrency Pattern in Go: A Comprehensive Visual Guide

Souvik Kar Mahapatra ・ Dec 29 '24

#go #tutorial #programming #architecture

In this post we'll cover Fan-in & Fan-out Pattern and will try to visualize them. So let's gear up as we'll be hands on through out the process.

gear up

Evolution from Pipeline Pattern

The fan-in fan-out pattern is a natural evolution of the pipeline pattern. While a pipeline processes data sequentially through stages, fan-in fan-out introduces parallel processing capabilities. Let's visualize how this evolution happens:

evolution of pipeline concurrency pattern to fan in & fan out concurrency pattern

Fan-In Fan-Out Pattern

Imagine a restaurant kitchen during busy hours. When orders come in, multiple cooks work on different dishes simultaneously (fan-out). As they complete dishes, they come together at the service counter (fan-in).

Fan in Fan out concurrency pattern visualized

Understanding Fan-out

Fan-out is distributing work across multiple goroutines to process data in parallel. Think of it as splitting a big task into smaller pieces that can be worked on simultaneously. Here's a simple example:

func fanOut(input 

<h3>
  
  
  Understanding Fan-in
</h3>

<p>Fan-in is the opposite of fan-out - it combines multiple input channels into a single channel. It's like a funnel that collects results from all workers into one stream. Here's how we implement it:<br>
</p>
<pre class="brush:php;toolbar:false">func fanIn(inputs ...


<p>Let's put it all together with a complete example that processes numbers in parallel:<br>
</p>
<pre class="brush:php;toolbar:false">func main() {
    // Create our input channel
    input := make(chan int)

    // Start sending numbers
    go func() {
        defer close(input)
        for i := 1; i 

<h2>
  
  
  Why Use Fan-in Fan-out Pattern?
</h2>

<p><strong>Optimal Resource Utilization</strong></p>

<p>The pattern naturally distributes work across available resources, this prevents idle resources,maximizing throughput.<br>
</p>
<pre class="brush:php;toolbar:false">// Worker pool size adapts to system resources
numWorkers := runtime.NumCPU()
if numWorkers > maxWorkers {
    numWorkers = maxWorkers // Prevent over-allocation
}
Copy after login

Improved Performance Through Parallelization

  • In the sequential approach, tasks are processed one after another, creating a linear execution time. If each task takes 1 second, processing 4 tasks takes 4 seconds.
  • This parallel processing reduces total execution time to approximately (total tasks / number of workers) overhead. In our example, with 4 workers, we process all tasks in about 1.2 seconds instead of 4 seconds.
func fanOut(tasks []Task) {
    numWorkers := runtime.NumCPU() // Utilize all available CPU cores
    workers := make([]

<h2>
  
  
  Real-World Use Cases
</h2>

<p><strong>Image Processing Pipeline</strong></p>

<p>It's like a upgrade from our pipeline pattern post, we need to process faster and have dedicated go routines from each process:</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173625991579012.png" class="lazy" alt="Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide processing pipeline with fan in and fan out pattern" loading="lazy"    style="max-width:90%"  style="max-width:90%"></p>

<p><strong>Web Scraper Pipeline</strong><br>
Web scraping is another perfect use case for fan-in fan-out.</p>

<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173625991836275.png" class="lazy" alt="Web scraping is another perfect use case for fan-in fan-out" loading="lazy"    style="max-width:90%"  style="max-width:90%"></p>

<p>The fan-in fan-out pattern really shines in these scenarios because it:</p>

Copy after login
  • Manages concurrency automatically through Go's channel mechanics
  • Provides natural backpressure when processing is slower than ingestion
  • Allows for easy scaling by adjusting the number of workers
  • Keeps the system resilient through isolated error handling

Error Handling Principles

Fail Fast: Detect and handle errors early in the pipeline

Try to perform all sort of validations before or at the start of the pipeline to make sure it doesn't fail down the line as it prevents wasting resources on invalid work that would fail later. It's especially crucial in fan-in fan-out patterns because invalid data could block workers or waste parallel processing capacity.

However it's not a hard rule and heavily depends on the business logic. Here is how we can implement it in out real-world examples:

func fanOut(input 


<p>and<br>
</p>
<pre class="brush:php;toolbar:false">func fanIn(inputs ...


<p>Notice! error in one worker the other do not stop, they keep processing and that brings us to 2nd principle</p>
<h3>
  
  
  Isolate Failures: One worker's error shouldn't affect others
</h3>

<p>In a parallel processing system, one bad task shouldn't bring down the entire system. Each worker should be independent.<br>
</p>
<pre class="brush:php;toolbar:false">func main() {
    // Create our input channel
    input := make(chan int)

    // Start sending numbers
    go func() {
        defer close(input)
        for i := 1; i 

<h4>
  
  
  Resource Cleanup: Proper cleanup on errors
</h4>

<p>Resource leaks in parallel processing can quickly escalate into system-wide issues. Proper cleanup is essential.</p>

<hr>

<p>That wraps up our deep dive into the Fan-In & Fan-Out pattern! Coming up next, we'll explore the <strong>Worker Pools concurrency pattern</strong>, which we got a glimpse of in this post. Like I said we are moving progressively clearing up dependencies before moving to the next one.</p>

<p>If you found this post helpful, have any questions, or want to share your own experiences with this pattern - I'd love to hear from you in the comments below. Your insights and questions help make these explanations even better for everyone.</p>

<p>If you missed out visual guide to Golang's goroutine and channels check it out here:</p>


<div>
  
    <div>
      <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173625990185651.png" class="lazy" alt="Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide" loading="lazy">
    </div>
<div>
      <h2 id="Understanding-and-visualizing-Goroutines-and-Channels-in-Golang">Understanding and visualizing Goroutines and Channels in Golang</h2>
      <h3 id="Souvik-Kar-Mahapatra-Dec">Souvik Kar Mahapatra ・ Dec 20 '24</h3>
      <div>
        #go
        #programming
        #learning
        #tutorial
      </div>
    </div>
  
</div>



<p>Stay tuned for more Go concurrency patterns! ?</p>

<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173625992371812.gif" class="lazy" alt="Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide" loading="lazy"    style="max-width:90%"  style="max-width:90%"></p>


          

            
  

            
        
Copy after login

The above is the detailed content of Fan-In Fan-Out Concurrency Pattern in Go: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles