System Design Academy

Saving…

Lesson 6 of 10 in Module 40 of 45 lessons complete

Semaphores

Module 4, lesson 6Concept12 min

Definition

Semaphore

In plain English
A semaphore is a counter that allows up to N goroutines into a section at the same time.
Think of it like
It is like a car park barrier that only lifts while spaces remain.

Why it exists

Starting 500 audio conversions together can exhaust memory. Only four should use the expensive encoder at once.

An insurer permits ten concurrent calls. Hold a slot for the entire call, then release it.

Token

In plain English
A token is an empty channel value representing one occupied semaphore slot.
Think of it like
Like a numbered ticket showing one space is in use.

context

In plain English
A context carries a cancellation signal and an optional deadline that every goroutine in a piece of work can watch.
Think of it like
It is like a fire alarm that tells everyone in the building to stop and leave.

How it works

Rate of concurrency vs rate limit

In plain English
Limiting concurrency caps how many tasks run at once, while a rate limit caps how many start per second.
Think of it like
Like a restaurant's table count versus how many guests the door lets in per minute.
  1. Acquire

    Send one token before starting a goroutine, so waiting jobs do not each need their own goroutine.

  2. Release

    Defer receiving that token back when the operation ends.

  3. Wait

    Wait for every started goroutine before returning.

Tasks enter Four slots before Working, which sends a release back to Four slots.

A completed operation returns its slot.

Tasks enter Four slots before Working, which sends a release back to Four slots.

After: at most 4 transcode operations run together.
Go
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	sem := make(chan struct{}, 4)
	var wg sync.WaitGroup
	for id := 1; id <= 8; id++ {
		sem <- struct{}{}
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			defer func() { <-sem }()
			time.Sleep(10 * time.Millisecond)
			fmt.Println("transcode", id)
		}(id)
	}
	wg.Wait()
}

Weighted permits

In plain English
Weighted permits let one operation reserve several semaphore slots at once.
Think of it like
Like a large vehicle taking two spaces.
Optional fragment: golang.org/x/sync/semaphore needs an external module; not compiled here.
Go
// Import golang.org/x/sync/semaphore in the surrounding file.
sem := semaphore.NewWeighted(4)
if err := sem.Acquire(ctx, 2); err != nil {
	return err
}
defer sem.Release(2)
// Work holds two of the four permits.

Examples

Cap expensive conversions

Eight episodes need conversion. Four encoder slots bound the expensive work.

After: at most 4 transcode operations run together.
Go
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	sem := make(chan struct{}, 4)
	var wg sync.WaitGroup
	for id := 1; id <= 8; id++ {
		sem <- struct{}{}
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			defer func() { <-sem }()
			time.Sleep(10 * time.Millisecond)
			fmt.Println("transcode", id)
		}(id)
	}
	wg.Wait()
}

Output order can vary. Acquiring before go also bounds the number of running helpers.

The insight

A buffered channel of size N can act as a semaphore.

Trade-offs

Pros

  • Bound expensive active work.
  • Respect downstream concurrency limits.

Cons

  • Missing releases permanently consume slots.
  • Requests per second remain unbounded.

Use when

  • Work uses scarce resources.
  • A service caps simultaneous calls.

Avoid when

  • Coordination costs more than the work.
  • A per-second limit is the actual requirement.

Quick check

What does make(chan struct{}, 4) give you when used as described?
A worker forgets to release its semaphore slot. Effect?

Takeaways

  • A semaphore caps active operations at N.
  • A buffered channel can hold semaphore tokens.
  • Always release acquired tokens with defer.

Try the quick check above whenever you feel ready.

Previous: Channels & select