Tutorials Design Patterns in C#
Publish-Subscribe Pattern — Complete Guide
Publish-Subscribe Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 44 of 69
Publish-Subscribe Pattern
GoF Core ✓ → Enterprise ✓ → Cloud & Craft
Cloud & Craft · 3 — Microservices & interviews · ~6 min · Module 5: Modern Enterprise Patterns
What is this?
Pub/Sub delivers messages from publishers to many subscribers via a broker or in-process bus — subscribers do not know each other.
Why should you care?
ShopNest order_placed fans out to inventory, email, and analytics independently.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public sealed class InProcBus
{
private readonly Dictionary<string, List<Action<string>>> _subs = new();
public void Subscribe(string topic, Action<string> handler)
{
if (!_subs.TryGetValue(topic, out var list)) _subs[topic] = list = new();
list.Add(handler);
}
public void Publish(string topic, string message)
{
if (_subs.TryGetValue(topic, out var list))
foreach (var h in list) h(message);
}
}
var bus = new InProcBus();
bus.Subscribe("order_placed", m => Console.WriteLine($"email {m}"));
bus.Subscribe("order_placed", m => Console.WriteLine($"index {m}"));
bus.Publish("order_placed", "o-9");
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- One publish notifies all subscribers.
- Production uses Rabbit/Kafka; the idea stays the same.
- Failures in one subscriber should not erase others (isolate).
Practice next
- Publish and see two handlers.
- Add analytics subscriber.
- Move to a real broker for cross-process.
- Unsubscribe a handler.
- Topic per event type.
Remember
One-to-many messaging. Loose coupling. Broker for distribution.
ShopNest order_placed fan-out
Bus notifies email + search.
Outcome: Email outage does not block indexing if isolated.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!