SlideShare a Scribd company logo
1
Go’s Context Library
By:
Smita Vijayakumar
Agenda
Introduction
-Context Management in
Distributed Systems
Go’s Context Library
Example Use case
Points to Watch Out For
2
1
2
3
4
3
Introduction
4
Distributed Data Flow
Request Processing
A B C
5
D E
RPC RPC RPC RPC
6
Go Context
• Defines *Context* type
• Carries request-scoped
values:
- Deadlines
- Cancellation signals
- Others
• Works across API
boundaries
- Also between processes
7
Details
type Context interface {
Done() <-chan struct{}

Err() error

Deadline() (deadline time.Time, ok bool)

Value(key interface{}) interface{}

}
8
1. Distributed Tracing
2. Request Cancellation
3. Context value
Primary
Use Cases
9
struct ContextValue {
requestID string
}
Example 1 - Distributed Tracing
10
Types of
Context Nodes
1. Background Node
2. Value Node
3. Cancellable Node
4. TODO() Node
Example -
A = context.Background()
B, cancelB = context.WithCancel(A)
C = context.WithValue(A, “C Key”, “C”)
D = context.WithValue(A, “D Key”, “D”)
E, cancelE = context.WithTimeout(B, timeout)
..
Background
Context
A
With
Value
C
With
Cancel
B
With
Value
D
With
Timeout
E
With
Value
F
With
Value
G
With
Value
11
H
With
Value
I
With
Value
J
Types - A Context Tree
12
package userid
const ctxKey string = “UserID”
func SetContextValue(ctx context.Context, id int) context.Context
{
return context.WithValue(ctx, ctxKey, id)
}
func GetContextValue(ctx context.Context) (int, bool) {
id, ok := ctx.Value(ctxKey).(int)
return id, ok
}
Example 2 - UTIL Package
13
package request
func startRequest(event *event.Event, timeout time.Duration) error {
ctx, cancel :=
context.WithTimeout(context.Background(), timeout)
defer cancel()
//…
ctx = util.SetContextValue(ctx, id)
status, err := processor.Server(ctx, event)
//…
}
Example 2 - Cancellable Request - Set the Context
14
package request
func startRequest(event *event.Event, timeout time.Duration) error {
ctx, cancel :=
context.WithTimeout(context.Background(), timeout)
defer cancel()
//…
ctx = util.SetContextValue(ctx, id)
status, err := processor.Server(ctx, event)
//…
}
Example 2 - Cancellable Request - Set the Context
15
package request
func startRequest(event *event.Event, timeout time.Duration) error {
ctx, cancel :=
context.WithTimeout(context.Background(), timeout)
defer cancel()
//…
ctx = util.SetContextValue(ctx, id)
status, err := processor.Server(ctx, event)
//…
}
Example 2 - Cancellable Request - Set the Context
16
package processor
func Server(ctx context.Context, event *event.Event) error {
if id, ok := util.FromContext(ctx); !ok {

return errors.New(“Not a valid ID to process”)

}
p := make(chan error, 1)
go func(ctx context.Context, id int,
event *event.Event) {
p <- processEvent(ctx, id, event)
}()
Example 2 - Cancellable Request – Get and Handle Context
17
package processor
func Server(ctx context.Context, event *event.Event) error {
if id, ok := util.FromContext(ctx); !ok {

return errors.New(“Not a valid ID to process”)

}
p := make(chan error, 1)
go func(ctx context.Context, id int,
event *event.Event) {
p <- processEvent(ctx, id, event)
}()
Example 2 - Cancellable Request – Get and Handle Context
18
//continued
select {
case <-ctx.Done():
//…
return ctx.Err()
case err := <-p
return err
}
}
Example 2 - Cancellable Request – Get and Handle Context
19
1. Ease of handling multiple,
concurrent requests
Summary -
Use Cases In
Distributed
System
2. Flow Traceability and
Fingerprinting
3. Time Sensitive and Cancellable
Request Processing
4. Ease of sending context
information
20
Remember!
21
Remember… For larger systems, complexity is
the downside
Code Complexity:
22
Difficult to actually implement
passing cancellable signals
downstream
Inter-Process Boundaries:
Remember…
23
Don’t store context variables
inside structures
Garbage Collection:
Remember…
24
Holding the right context node
Querying:
Remember…
25
Thank you!
For any queries:
Smita Vijayakumar smita@exotel.in

More Related Content

PDF
Use Kotlin scripts and Clova SDK to build your Clova extension
TXT
Codeofdatabase
TXT
New text document
PPTX
Using Change Streams to Keep Up with Your Data
PPTX
Correcting Common Async/Await Mistakes in .NET
PDF
Trisha gee concurrentprogrammingusingthedisruptor
PPTX
Asynchronous programming
PPTX
Introduction to Service Workers | Matteo Manchi
Use Kotlin scripts and Clova SDK to build your Clova extension
Codeofdatabase
New text document
Using Change Streams to Keep Up with Your Data
Correcting Common Async/Await Mistakes in .NET
Trisha gee concurrentprogrammingusingthedisruptor
Asynchronous programming
Introduction to Service Workers | Matteo Manchi

What's hot (20)

PPTX
Smart Contract programming 101 with Solidity #PizzaHackathon
PPTX
No More Deadlocks; Asynchronous Programming in .NET
PPTX
Dex and Uniswap
PPTX
Correcting Common .NET Async/Await Mistakes
PPTX
Using Cerberus and PySpark to validate semi-structured datasets
PDF
Fetch data from form
PDF
Minion pool - a worker pool for nodejs
PPTX
Apache Spark in your likeness - low and high level customization
PDF
FwDays 2021: Metarhia Technology Stack for Node.js
PDF
Monitoring und Metriken im Wunderland
 
PPTX
Apache Spark Structured Streaming + Apache Kafka = ♡
PDF
Do something in 5 with gas 9-copy between databases with oauth2
PDF
Async Microservices with Twitter's Finagle
PPTX
Blockchain and smart contracts day 2
PDF
Nestjs MasterClass Slides
PPTX
What is row level isolation on cassandra
PDF
ClojureScript for the web
PDF
ClojureScript loves React, DomCode May 26 2015
PDF
dSS API by example
PPTX
Hands on with smart contracts 2. Presentation for the Blockchain Applications...
Smart Contract programming 101 with Solidity #PizzaHackathon
No More Deadlocks; Asynchronous Programming in .NET
Dex and Uniswap
Correcting Common .NET Async/Await Mistakes
Using Cerberus and PySpark to validate semi-structured datasets
Fetch data from form
Minion pool - a worker pool for nodejs
Apache Spark in your likeness - low and high level customization
FwDays 2021: Metarhia Technology Stack for Node.js
Monitoring und Metriken im Wunderland
 
Apache Spark Structured Streaming + Apache Kafka = ♡
Do something in 5 with gas 9-copy between databases with oauth2
Async Microservices with Twitter's Finagle
Blockchain and smart contracts day 2
Nestjs MasterClass Slides
What is row level isolation on cassandra
ClojureScript for the web
ClojureScript loves React, DomCode May 26 2015
dSS API by example
Hands on with smart contracts 2. Presentation for the Blockchain Applications...
Ad

Viewers also liked (20)

PPTX
Setting A Culture of Technical Excellence
PDF
Working at Exotel
PDF
Exotel For Last Mile Logistics
PPTX
Cloud Communication for E-commerce & Last Mile Logistics
PDF
Monitor PowerKVM using Ganglia, Nagios
PDF
One-click Hadoop Cluster Deployment on OpenPOWER Systems
ODP
Gluster containers!
ODP
Comment travailler avec les logiciels Open Source
PDF
Meetup Systemd vs sysvinit
PPTX
BibBase Linked Data Triplification Challenge 2010 Presentation
ODP
ERTS 2008 - Using Linux for industrial projects
PDF
ERTS 2008 - Using Linux for industrial projects
ODP
Créer une distribution Linux embarqué professionnelle avec Yocto Project
PDF
Open Embedded un framework libre pour assurer la cohérence de son projet
PDF
Présentation Yocto - SophiaConf 2015
PDF
Yocto une solution robuste pour construire des applications à fort contenu ap...
ODP
OS libres pour l'IoT - Zephyr
PDF
PDF
Gluster Contenarized Storage for Cloud Applications
PPTX
Using heka
Setting A Culture of Technical Excellence
Working at Exotel
Exotel For Last Mile Logistics
Cloud Communication for E-commerce & Last Mile Logistics
Monitor PowerKVM using Ganglia, Nagios
One-click Hadoop Cluster Deployment on OpenPOWER Systems
Gluster containers!
Comment travailler avec les logiciels Open Source
Meetup Systemd vs sysvinit
BibBase Linked Data Triplification Challenge 2010 Presentation
ERTS 2008 - Using Linux for industrial projects
ERTS 2008 - Using Linux for industrial projects
Créer une distribution Linux embarqué professionnelle avec Yocto Project
Open Embedded un framework libre pour assurer la cohérence de son projet
Présentation Yocto - SophiaConf 2015
Yocto une solution robuste pour construire des applications à fort contenu ap...
OS libres pour l'IoT - Zephyr
Gluster Contenarized Storage for Cloud Applications
Using heka
Ad

Similar to #Gophercon Talk by Smita Vijayakumar - Go's Context Library (20)

PDF
Online Meetup: Why should container system / platform builders care about con...
PDF
用 Go 語言打造多台機器 Scale 架構
PDF
Azure Durable Functions (2019-03-30)
PDF
gRPC in Go
PDF
GraphQL Bangkok Meetup 2.0
PDF
Architecting Alive Apps
PDF
Job Queue in Golang
PDF
Azure Durable Functions (2019-04-27)
PDF
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
PDF
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
PPTX
Codable routing
PDF
Durable functions 2.0 (2019-10-10)
PPTX
Intro to Node
PPTX
分散式系統
PDF
Streaming Data with scalaz-stream
ODP
Finagle and Java Service Framework at Pinterest
PDF
A deep dive into PEP-3156 and the new asyncio module
PDF
外部環境への依存をテストする
PPTX
Context Information Management in IoT enabled smart systems - the basics
PDF
Live Streaming & Server Sent Events
Online Meetup: Why should container system / platform builders care about con...
用 Go 語言打造多台機器 Scale 架構
Azure Durable Functions (2019-03-30)
gRPC in Go
GraphQL Bangkok Meetup 2.0
Architecting Alive Apps
Job Queue in Golang
Azure Durable Functions (2019-04-27)
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Codable routing
Durable functions 2.0 (2019-10-10)
Intro to Node
分散式系統
Streaming Data with scalaz-stream
Finagle and Java Service Framework at Pinterest
A deep dive into PEP-3156 and the new asyncio module
外部環境への依存をテストする
Context Information Management in IoT enabled smart systems - the basics
Live Streaming & Server Sent Events

More from Exotel (9)

PDF
Exotel cost of moving to cloud
PDF
(Webinar) E-commerce delivery lifecycle - How to streamline communication
PPT
Introduction to Go programming
PPTX
Exotel - Cloud telephony, Business phone system experts
PDF
E-Commerce Call Trends in India Report
ODP
To Sell Is Human: The Surprising Truth About Moving Others - a summary
PPSX
Exotel Culture Code
PPT
Customer Development @ SLP Mumbai by Ruchir
PDF
Nasscom Product Conclave - How to get your first 20 customers
Exotel cost of moving to cloud
(Webinar) E-commerce delivery lifecycle - How to streamline communication
Introduction to Go programming
Exotel - Cloud telephony, Business phone system experts
E-Commerce Call Trends in India Report
To Sell Is Human: The Surprising Truth About Moving Others - a summary
Exotel Culture Code
Customer Development @ SLP Mumbai by Ruchir
Nasscom Product Conclave - How to get your first 20 customers

Recently uploaded (20)

PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
OOP with Java - Java Introduction (Basics)
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Sustainable Sites - Green Building Construction
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Geodesy 1.pptx...............................................
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
additive manufacturing of ss316l using mig welding
PPT
Mechanical Engineering MATERIALS Selection
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
UNIT 4 Total Quality Management .pptx
bas. eng. economics group 4 presentation 1.pptx
OOP with Java - Java Introduction (Basics)
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Sustainable Sites - Green Building Construction
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Foundation to blockchain - A guide to Blockchain Tech
Geodesy 1.pptx...............................................
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
additive manufacturing of ss316l using mig welding
Mechanical Engineering MATERIALS Selection
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf

#Gophercon Talk by Smita Vijayakumar - Go's Context Library

  • 2. Agenda Introduction -Context Management in Distributed Systems Go’s Context Library Example Use case Points to Watch Out For 2 1 2 3 4
  • 5. Request Processing A B C 5 D E RPC RPC RPC RPC
  • 6. 6 Go Context • Defines *Context* type • Carries request-scoped values: - Deadlines - Cancellation signals - Others • Works across API boundaries - Also between processes
  • 7. 7 Details type Context interface { Done() <-chan struct{}
 Err() error
 Deadline() (deadline time.Time, ok bool)
 Value(key interface{}) interface{}
 }
  • 8. 8 1. Distributed Tracing 2. Request Cancellation 3. Context value Primary Use Cases
  • 9. 9 struct ContextValue { requestID string } Example 1 - Distributed Tracing
  • 10. 10 Types of Context Nodes 1. Background Node 2. Value Node 3. Cancellable Node 4. TODO() Node
  • 11. Example - A = context.Background() B, cancelB = context.WithCancel(A) C = context.WithValue(A, “C Key”, “C”) D = context.WithValue(A, “D Key”, “D”) E, cancelE = context.WithTimeout(B, timeout) .. Background Context A With Value C With Cancel B With Value D With Timeout E With Value F With Value G With Value 11 H With Value I With Value J Types - A Context Tree
  • 12. 12 package userid const ctxKey string = “UserID” func SetContextValue(ctx context.Context, id int) context.Context { return context.WithValue(ctx, ctxKey, id) } func GetContextValue(ctx context.Context) (int, bool) { id, ok := ctx.Value(ctxKey).(int) return id, ok } Example 2 - UTIL Package
  • 13. 13 package request func startRequest(event *event.Event, timeout time.Duration) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() //… ctx = util.SetContextValue(ctx, id) status, err := processor.Server(ctx, event) //… } Example 2 - Cancellable Request - Set the Context
  • 14. 14 package request func startRequest(event *event.Event, timeout time.Duration) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() //… ctx = util.SetContextValue(ctx, id) status, err := processor.Server(ctx, event) //… } Example 2 - Cancellable Request - Set the Context
  • 15. 15 package request func startRequest(event *event.Event, timeout time.Duration) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() //… ctx = util.SetContextValue(ctx, id) status, err := processor.Server(ctx, event) //… } Example 2 - Cancellable Request - Set the Context
  • 16. 16 package processor func Server(ctx context.Context, event *event.Event) error { if id, ok := util.FromContext(ctx); !ok {
 return errors.New(“Not a valid ID to process”)
 } p := make(chan error, 1) go func(ctx context.Context, id int, event *event.Event) { p <- processEvent(ctx, id, event) }() Example 2 - Cancellable Request – Get and Handle Context
  • 17. 17 package processor func Server(ctx context.Context, event *event.Event) error { if id, ok := util.FromContext(ctx); !ok {
 return errors.New(“Not a valid ID to process”)
 } p := make(chan error, 1) go func(ctx context.Context, id int, event *event.Event) { p <- processEvent(ctx, id, event) }() Example 2 - Cancellable Request – Get and Handle Context
  • 18. 18 //continued select { case <-ctx.Done(): //… return ctx.Err() case err := <-p return err } } Example 2 - Cancellable Request – Get and Handle Context
  • 19. 19 1. Ease of handling multiple, concurrent requests Summary - Use Cases In Distributed System 2. Flow Traceability and Fingerprinting 3. Time Sensitive and Cancellable Request Processing 4. Ease of sending context information
  • 21. 21 Remember… For larger systems, complexity is the downside Code Complexity:
  • 22. 22 Difficult to actually implement passing cancellable signals downstream Inter-Process Boundaries: Remember…
  • 23. 23 Don’t store context variables inside structures Garbage Collection: Remember…
  • 24. 24 Holding the right context node Querying: Remember…
  • 25. 25 Thank you! For any queries: Smita Vijayakumar smita@exotel.in