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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

See all articles