SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Smart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathonSmart Contract programming 101 with Solidity #PizzaHackathon
Smart Contract programming 101 with Solidity #PizzaHackathonSittiphol Phanvilai
 
No More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETNo More Deadlocks; Asynchronous Programming in .NET
No More Deadlocks; Asynchronous Programming in .NETFilip Ekberg
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesBrandon Minnick, MBA
 
Using Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsUsing Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsBartosz Konieczny
 
Minion pool - a worker pool for nodejs
Minion pool - a worker pool for nodejsMinion pool - a worker pool for nodejs
Minion pool - a worker pool for nodejsMarcelo Gornstein
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationBartosz Konieczny
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsTimur Shemsedinov
 
Monitoring und Metriken im Wunderland
Monitoring und Metriken im WunderlandMonitoring und Metriken im Wunderland
Monitoring und Metriken im WunderlandD
 
Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Bartosz Konieczny
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Bruce McPherson
 
Async Microservices with Twitter's Finagle
Async Microservices with Twitter's FinagleAsync Microservices with Twitter's Finagle
Async Microservices with Twitter's FinagleVladimir Kostyukov
 
Blockchain and smart contracts day 2
Blockchain and smart contracts day 2Blockchain and smart contracts day 2
Blockchain and smart contracts day 2Gene Leybzon
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
What is row level isolation on cassandra
What is row level isolation on cassandraWhat is row level isolation on cassandra
What is row level isolation on cassandraKazutaka Tomita
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Hands on with smart contracts 2. Presentation for the Blockchain Applications...
Hands on with smart contracts 2. Presentation for the Blockchain Applications...Hands on with smart contracts 2. Presentation for the Blockchain Applications...
Hands on with smart contracts 2. Presentation for the Blockchain Applications...Gene Leybzon
 

Tendances (20)

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

En vedette

Setting A Culture of Technical Excellence
Setting A Culture of Technical ExcellenceSetting A Culture of Technical Excellence
Setting A Culture of Technical ExcellenceExotel
 
Working at Exotel
Working at ExotelWorking at Exotel
Working at ExotelExotel
 
Exotel For Last Mile Logistics
Exotel For Last Mile LogisticsExotel For Last Mile Logistics
Exotel For Last Mile LogisticsExotel
 
Cloud Communication for E-commerce & Last Mile Logistics
Cloud Communication for E-commerce & Last Mile LogisticsCloud Communication for E-commerce & Last Mile Logistics
Cloud Communication for E-commerce & Last Mile LogisticsExotel
 
Monitor PowerKVM using Ganglia, Nagios
Monitor PowerKVM using Ganglia, NagiosMonitor PowerKVM using Ganglia, Nagios
Monitor PowerKVM using Ganglia, NagiosPradeep Kumar
 
One-click Hadoop Cluster Deployment on OpenPOWER Systems
One-click Hadoop Cluster Deployment on OpenPOWER SystemsOne-click Hadoop Cluster Deployment on OpenPOWER Systems
One-click Hadoop Cluster Deployment on OpenPOWER SystemsPradeep Kumar
 
Comment travailler avec les logiciels Open Source
Comment travailler avec les logiciels Open SourceComment travailler avec les logiciels Open Source
Comment travailler avec les logiciels Open SourceChristian Charreyre
 
BibBase Linked Data Triplification Challenge 2010 Presentation
BibBase Linked Data Triplification Challenge 2010 PresentationBibBase Linked Data Triplification Challenge 2010 Presentation
BibBase Linked Data Triplification Challenge 2010 PresentationReynold Xin
 
ERTS 2008 - Using Linux for industrial projects
ERTS 2008 - Using Linux for industrial projectsERTS 2008 - Using Linux for industrial projects
ERTS 2008 - Using Linux for industrial projectsChristian Charreyre
 
ERTS 2008 - Using Linux for industrial projects
ERTS 2008 - Using Linux for industrial projectsERTS 2008 - Using Linux for industrial projects
ERTS 2008 - Using Linux for industrial projectsChristian Charreyre
 
Créer une distribution Linux embarqué professionnelle avec Yocto Project
Créer une distribution Linux embarqué professionnelle avec Yocto ProjectCréer une distribution Linux embarqué professionnelle avec Yocto Project
Créer une distribution Linux embarqué professionnelle avec Yocto ProjectChristian Charreyre
 
Open Embedded un framework libre pour assurer la cohérence de son projet
Open Embedded un framework libre pour assurer la cohérence de son projetOpen Embedded un framework libre pour assurer la cohérence de son projet
Open Embedded un framework libre pour assurer la cohérence de son projetChristian Charreyre
 
Présentation Yocto - SophiaConf 2015
Présentation Yocto - SophiaConf 2015Présentation Yocto - SophiaConf 2015
Présentation Yocto - SophiaConf 2015Christian Charreyre
 
Yocto une solution robuste pour construire des applications à fort contenu ap...
Yocto une solution robuste pour construire des applications à fort contenu ap...Yocto une solution robuste pour construire des applications à fort contenu ap...
Yocto une solution robuste pour construire des applications à fort contenu ap...Christian Charreyre
 
Gluster Contenarized Storage for Cloud Applications
Gluster Contenarized Storage for Cloud ApplicationsGluster Contenarized Storage for Cloud Applications
Gluster Contenarized Storage for Cloud ApplicationsHumble Chirammal
 
Using heka
Using hekaUsing heka
Using hekaExotel
 

En vedette (20)

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

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

Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Docker, Inc.
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構Bo-Yi Wu
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Paco de la Cruz
 
GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0Tobias Meixner
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive AppsJorge Ortiz
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Paco de la Cruz
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Paco de la Cruz
 
Streaming Data with scalaz-stream
Streaming Data with scalaz-streamStreaming Data with scalaz-stream
Streaming Data with scalaz-streamGaryCoady
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
外部環境への依存をテストする
外部環境への依存をテストする外部環境への依存をテストする
外部環境への依存をテストするShunsuke Maeda
 
Context Information Management in IoT enabled smart systems - the basics
Context Information Management in IoT enabled smart systems - the basicsContext Information Management in IoT enabled smart systems - the basics
Context Information Management in IoT enabled smart systems - the basicsFernando Lopez Aguilar
 
Live Streaming & Server Sent Events
Live Streaming & Server Sent EventsLive Streaming & Server Sent Events
Live Streaming & Server Sent Eventstkramar
 

Similaire à #Gophercon Talk by Smita Vijayakumar - Go's Context Library (20)

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

Plus de Exotel

Exotel cost of moving to cloud
Exotel cost of moving to cloudExotel cost of moving to cloud
Exotel cost of moving to cloudExotel
 
(Webinar) E-commerce delivery lifecycle - How to streamline communication
(Webinar) E-commerce delivery lifecycle - How to streamline communication(Webinar) E-commerce delivery lifecycle - How to streamline communication
(Webinar) E-commerce delivery lifecycle - How to streamline communicationExotel
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programmingExotel
 
Exotel - Cloud telephony, Business phone system experts
Exotel - Cloud telephony, Business phone system expertsExotel - Cloud telephony, Business phone system experts
Exotel - Cloud telephony, Business phone system expertsExotel
 
E-Commerce Call Trends in India Report
E-Commerce Call Trends in India ReportE-Commerce Call Trends in India Report
E-Commerce Call Trends in India ReportExotel
 
To Sell Is Human: The Surprising Truth About Moving Others - a summary
To Sell Is Human: The Surprising Truth About Moving Others - a summaryTo Sell Is Human: The Surprising Truth About Moving Others - a summary
To Sell Is Human: The Surprising Truth About Moving Others - a summaryExotel
 
Exotel Culture Code
Exotel Culture CodeExotel Culture Code
Exotel Culture CodeExotel
 
Customer Development @ SLP Mumbai by Ruchir
Customer Development @ SLP Mumbai by RuchirCustomer Development @ SLP Mumbai by Ruchir
Customer Development @ SLP Mumbai by RuchirExotel
 
Nasscom Product Conclave - How to get your first 20 customers
Nasscom Product Conclave - How to get your first 20 customersNasscom Product Conclave - How to get your first 20 customers
Nasscom Product Conclave - How to get your first 20 customersExotel
 

Plus de Exotel (9)

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

Dernier

Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stageAbc194748
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...HenryBriggs2
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxnuruddin69
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 

Dernier (20)

Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

#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