SlideShare a Scribd company logo
1 of 22
Download to read offline
Understanding Go Memory
September 11, 2013

John Graham-Cumming

www.cloudflare.com!
Allocation Primitives
•  new(T)!
•  Allocates memory for item with type T!
•  Zeroes it

zeroed

ret = runtime·mallocgc(typ->size, flag, 1, 1);!


!
•  make(T)!
•  Allocates memory for item with type T!
•  Initializes it
•  Needed for channels, maps and slices

•  Memory comes from internal heap

www.cloudflare.com!
Two memory freeing processes 

•  Garbage collection
•  Determines which blocks of memory are no longer used
•  Marks areas of heap so they can be reused by your program

•  Scavenging
•  Determines when parts of the heap are idle for a long time
•  Returns memory to the operation system

www.cloudflare.com!
Garbage collection
•  Controlled by the GOGC environment variable
•  And by debug.SetGCPercentage()!
// Initialized from $GOGC. GOGC=off means no gc.!
//!
// Next gc is after we've allocated an extra amount of!
// memory proportional to the amount already in use.!
// If gcpercent=100 and we're using 4M, we'll gc again!
// when we get to 8M. This keeps the gc cost in linear!
// proportion to the allocation cost. Adjusting gcpercent!
// just changes the linear constant (and also the amount of!
// extra memory used).!
•  Default is same as GOGC=100!
•  Can set GOGC=off or debug.SetGCPercentage(-1) (no

garbage collection at all)

www.cloudflare.com!
Scavenging
•  Runs once per minute
// If we go two minutes without a garbage collection, !
// force one to run.!
forcegc = 2*60*1e9;!
!
// If a span goes unused for 5 minutes after a garbage!
// collection, we hand it back to the operating system.!
limit = 5*60*1e9;!

•  Can also force return of all unused memory by calling

debug.FreeOSMemory()!

www.cloudflare.com!
Memory Statistics
•  Read with runtime.ReadMemStats(&m)


!
•  The MemStats struct has tons of members
•  Useful ones for looking at heap
•  HeapInuse - # bytes in the heap allocated to things
•  HeapIdle - # bytes in heap waiting to be used
•  HeapSys - # bytes obtained from OS
•  HeapReleased - # bytes released to OS



www.cloudflare.com!
Test garbage making program
func makeBuffer() []byte { !
return make([]byte, rand.Intn(5000000)+5000000)
}!
!
func main() { !
pool := make([][]byte, 20)!
!
makes := 0 !
for { !
b := makeBuffer()

makes += 1!
!
i := rand.Intn(len(pool))!
pool[i] = b!
!
time.Sleep(time.Second)!
}!
}!
www.cloudflare.com!

!
What happens

www.cloudflare.com!
debug.FreeOSMemory()!

www.cloudflare.com!
Use a buffered channel
func main() {!
pool := make([][]byte, 20)!
idle:= make(chan []byte, 5)!
!
makes := 0!
for {!
var b []byte!
select {!
case b = <-idle:!
default:!
makes += 1!
b = makeBuffer()!
}!
!
!
!
!

i := rand.Intn(len(pool))!
if pool[i] != nil {!
select {!
case idle<- pool[i]:!
pool[i] = nil!
default:!
}!
}!
pool[i] = b!
time.Sleep(time.Second)!
}!

}
www.cloudflare.com!
select for non-blocking receive
A buffered
channel makes a
simple queue
idle:= make(chan []byte, 5)!
!
select {!
case b = <-idle:

!
default:!
Try to get from the
makes += 1!
idle queue
b = makeBuffer()!
}!

Idle queue
empty? Make a
new buffer
www.cloudflare.com!
select for non-blocking send
A buffered
channel makes a
simple queue
idle:= make(chan []byte, 5)!
!
select {!
case buffer <- pool[i]:!
pool[i] = nil!
!
Try to return buffer
default:!
to the idle queue
}!

Idle queue full?
GC will have to
deal with the
buffer
www.cloudflare.com!
What happens

www.cloudflare.com!
More realistic: 20 goroutines
func main() {!
pool := make([][]byte, 200)!
!
for i := 0; i < 10; i++ {!
go func(offset int) {!
for {!
b := makeBuffer()!
j := offset+rand.Intn(20)!
pool[j] = b!
!
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))!
}!
}(i*20)!
}!
}!

www.cloudflare.com!
What happens

www.cloudflare.com!
Shared across goroutines
func main() {!
buffer := make(chan []byte, 5)!
!
pool := make([][]byte, 200)!
for i := 0; i < 10; i++ {!
go func(offset int) {!
for {!
var b []byte!
select {!
case b = <-buffer:!
default: b = makeBuffer()!
}!
j := offset+rand.Intn(20)!
if pool[j] != nil {!
select {!
case buffer <- pool[j]: pool[j] = nil!
default:!
}!
}!
pool[j] = b!
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))!
}!
}(i*20)!
}!
!
www.cloudflare.com!
What Happens

www.cloudflare.com!
More realistic example
•  Alter code to
•  Always try to give back a random buffer from the pool
•  50% of the time get a new one
•  Should create more garbage

www.cloudflare.com!
Idle length 5

www.cloudflare.com!
Idle length 20

www.cloudflare.com!
Idle length 50

www.cloudflare.com!
Also
•  This works for things other than []byte
•  Can be done with arbitrary types
•  Just need some way to reset
•  There’s a proposal to add something like this to the Go

package library
•  sync.Cache
•  Follow TODO

www.cloudflare.com!

More Related Content

What's hot

Rapid Application Design in Financial Services
Rapid Application Design in Financial ServicesRapid Application Design in Financial Services
Rapid Application Design in Financial ServicesAerospike
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badooMarko Kevac
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyAerospike
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to GoCloudflare
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performancesource{d}
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go ConcurrencyCloudflare
 
Ceph Day Shanghai - Ceph Performance Tools
Ceph Day Shanghai - Ceph Performance Tools Ceph Day Shanghai - Ceph Performance Tools
Ceph Day Shanghai - Ceph Performance Tools Ceph Community
 
MongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDBMongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDBBoxed Ice
 
Commit2015 kharchenko - python generators - ext
Commit2015   kharchenko - python generators - extCommit2015   kharchenko - python generators - ext
Commit2015 kharchenko - python generators - extMaxym Kharchenko
 
Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Maarten Mulders
 
Event Loop in Javascript
Event Loop in JavascriptEvent Loop in Javascript
Event Loop in JavascriptDiptiGandhi4
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
Apache Hadoop for System Administrators
Apache Hadoop for System AdministratorsApache Hadoop for System Administrators
Apache Hadoop for System AdministratorsAllen Wittenauer
 
Мониторинг. Опять, rootconf 2016
Мониторинг. Опять, rootconf 2016Мониторинг. Опять, rootconf 2016
Мониторинг. Опять, rootconf 2016Vsevolod Polyakov
 
Rubyslava + PyVo #48
Rubyslava + PyVo #48Rubyslava + PyVo #48
Rubyslava + PyVo #48Jozef Képesi
 

What's hot (20)

Rapid Application Design in Financial Services
Rapid Application Design in Financial ServicesRapid Application Design in Financial Services
Rapid Application Design in Financial Services
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
 
Event loop
Event loopEvent loop
Event loop
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performance
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
2015 555 kharchenko_ppt
2015 555 kharchenko_ppt2015 555 kharchenko_ppt
2015 555 kharchenko_ppt
 
Ceph Day Shanghai - Ceph Performance Tools
Ceph Day Shanghai - Ceph Performance Tools Ceph Day Shanghai - Ceph Performance Tools
Ceph Day Shanghai - Ceph Performance Tools
 
MongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDBMongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDB
 
GoLang & GoatCore
GoLang & GoatCore GoLang & GoatCore
GoLang & GoatCore
 
Commit2015 kharchenko - python generators - ext
Commit2015   kharchenko - python generators - extCommit2015   kharchenko - python generators - ext
Commit2015 kharchenko - python generators - ext
 
Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)
 
Event Loop in Javascript
Event Loop in JavascriptEvent Loop in Javascript
Event Loop in Javascript
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Apache Hadoop for System Administrators
Apache Hadoop for System AdministratorsApache Hadoop for System Administrators
Apache Hadoop for System Administrators
 
Metrics: where and how
Metrics: where and howMetrics: where and how
Metrics: where and how
 
Мониторинг. Опять, rootconf 2016
Мониторинг. Опять, rootconf 2016Мониторинг. Опять, rootconf 2016
Мониторинг. Опять, rootconf 2016
 
Jk rubyslava 25
Jk rubyslava 25Jk rubyslava 25
Jk rubyslava 25
 
Rubyslava + PyVo #48
Rubyslava + PyVo #48Rubyslava + PyVo #48
Rubyslava + PyVo #48
 

Viewers also liked

Spring 2 cooke
Spring 2 cookeSpring 2 cooke
Spring 2 cookeSimpony
 
Dualacy chap 2 soph
Dualacy chap 2 sophDualacy chap 2 soph
Dualacy chap 2 sophSimpony
 
Peoplepro Management Services Pvt. Ltd.
Peoplepro Management Services Pvt. Ltd.Peoplepro Management Services Pvt. Ltd.
Peoplepro Management Services Pvt. Ltd.anibandha
 
Srana Consulting - CIO On Demand
Srana Consulting - CIO On DemandSrana Consulting - CIO On Demand
Srana Consulting - CIO On Demandanibandha
 
To The President Of SIMT
 To The President Of SIMT To The President Of SIMT
To The President Of SIMTVipin Kumar
 
Koike's_work_style.pdf
Koike's_work_style.pdfKoike's_work_style.pdf
Koike's_work_style.pdfTomokazuKoike
 
Pregnancy four
Pregnancy fourPregnancy four
Pregnancy fourSimpony
 
CMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; AntoniadouCMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; AntoniadouCmcTchrEdSIG
 
Dualacy chap 2 winter
Dualacy chap 2 winterDualacy chap 2 winter
Dualacy chap 2 winterSimpony
 
Architectural arcadia
Architectural arcadiaArchitectural arcadia
Architectural arcadiaDevon Tl
 
Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011vinillaxue
 
Dfx oss 00225-a_co_p-2011_final
Dfx oss 00225-a_co_p-2011_finalDfx oss 00225-a_co_p-2011_final
Dfx oss 00225-a_co_p-2011_finalvinillaxue
 
La luna y la vaca
La luna y la vacaLa luna y la vaca
La luna y la vacaginasua
 
rowell resperatory powerpiont
rowell resperatory powerpiont rowell resperatory powerpiont
rowell resperatory powerpiont rowellcabate
 
Fabulares ii paying debts
Fabulares ii paying debtsFabulares ii paying debts
Fabulares ii paying debtsSimpony
 

Viewers also liked (19)

2pac
2pac2pac
2pac
 
Spring 2 cooke
Spring 2 cookeSpring 2 cooke
Spring 2 cooke
 
Dualacy chap 2 soph
Dualacy chap 2 sophDualacy chap 2 soph
Dualacy chap 2 soph
 
Peoplepro Management Services Pvt. Ltd.
Peoplepro Management Services Pvt. Ltd.Peoplepro Management Services Pvt. Ltd.
Peoplepro Management Services Pvt. Ltd.
 
lecture3
lecture3lecture3
lecture3
 
Srana Consulting - CIO On Demand
Srana Consulting - CIO On DemandSrana Consulting - CIO On Demand
Srana Consulting - CIO On Demand
 
To The President Of SIMT
 To The President Of SIMT To The President Of SIMT
To The President Of SIMT
 
Koike's_work_style.pdf
Koike's_work_style.pdfKoike's_work_style.pdf
Koike's_work_style.pdf
 
Mentor family
Mentor familyMentor family
Mentor family
 
Pregnancy four
Pregnancy fourPregnancy four
Pregnancy four
 
CMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; AntoniadouCMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; Antoniadou
 
Dualacy chap 2 winter
Dualacy chap 2 winterDualacy chap 2 winter
Dualacy chap 2 winter
 
Architectural arcadia
Architectural arcadiaArchitectural arcadia
Architectural arcadia
 
Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011
 
Dfx oss 00225-a_co_p-2011_final
Dfx oss 00225-a_co_p-2011_finalDfx oss 00225-a_co_p-2011_final
Dfx oss 00225-a_co_p-2011_final
 
La luna y la vaca
La luna y la vacaLa luna y la vaca
La luna y la vaca
 
My Classes
My ClassesMy Classes
My Classes
 
rowell resperatory powerpiont
rowell resperatory powerpiont rowell resperatory powerpiont
rowell resperatory powerpiont
 
Fabulares ii paying debts
Fabulares ii paying debtsFabulares ii paying debts
Fabulares ii paying debts
 

Similar to Go Memory

OS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switchOS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switchDaniel Ben-Zvi
 
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupДоклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupBadoo Development
 
GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.Timothy Tsvetkov
 
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek GrębskiJDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek GrębskiPROIDEA
 
On heap cache vs off-heap cache
On heap cache vs off-heap cacheOn heap cache vs off-heap cache
On heap cache vs off-heap cachergrebski
 
Unity - Internals: memory and performance
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performanceCodemotion
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...
Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...
Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...Jean-Philippe BEMPEL
 
Compromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging MechanismsCompromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging MechanismsRussell Sanford
 
The origin: Init (compact version)
The origin: Init (compact version)The origin: Init (compact version)
The origin: Init (compact version)Tzung-Bi Shih
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?C2B2 Consulting
 
High Performance With Java
High Performance With JavaHigh Performance With Java
High Performance With Javamalduarte
 

Similar to Go Memory (20)

Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe
 
OS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switchOS scheduling and The anatomy of a context switch
OS scheduling and The anatomy of a context switch
 
Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
 
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang MeetupДоклад Антона Поварова "Go in Badoo" с Golang Meetup
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
 
GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.GC in Ruby. RubyC, Kiev, 2014.
GC in Ruby. RubyC, Kiev, 2014.
 
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek GrębskiJDD2015: On-heap cache vs Off-heap cache - Radek Grębski
JDD2015: On-heap cache vs Off-heap cache - Radek Grębski
 
On heap cache vs off-heap cache
On heap cache vs off-heap cacheOn heap cache vs off-heap cache
On heap cache vs off-heap cache
 
Objective-c memory
Objective-c memoryObjective-c memory
Objective-c memory
 
Unity - Internals: memory and performance
Unity - Internals: memory and performanceUnity - Internals: memory and performance
Unity - Internals: memory and performance
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...
Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...
Javaday 2022 - Remèdes aux oomkill, warm-ups, et lenteurs pour des conteneur...
 
Compromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging MechanismsCompromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging Mechanisms
 
The origin: Init (compact version)
The origin: Init (compact version)The origin: Init (compact version)
The origin: Init (compact version)
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?G1 Garbage Collector - Big Heaps and Low Pauses?
G1 Garbage Collector - Big Heaps and Low Pauses?
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
Storm Anatomy
Storm AnatomyStorm Anatomy
Storm Anatomy
 
High Performance With Java
High Performance With JavaHigh Performance With Java
High Performance With Java
 
Small Screen Development
Small Screen DevelopmentSmall Screen Development
Small Screen Development
 

More from Cloudflare

Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)Cloudflare
 
Close your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with CloudflareClose your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with CloudflareCloudflare
 
Why you should replace your d do s hardware appliance
Why you should replace your d do s hardware applianceWhy you should replace your d do s hardware appliance
Why you should replace your d do s hardware applianceCloudflare
 
Don't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable WebinarDon't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable WebinarCloudflare
 
Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021Cloudflare
 
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...Cloudflare
 
Zero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fastZero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fastCloudflare
 
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...Cloudflare
 
Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...Cloudflare
 
Scaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-serviceScaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-serviceCloudflare
 
Application layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare dataApplication layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare dataCloudflare
 
Recent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respondRecent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respondCloudflare
 
Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)Cloudflare
 
Strengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providersStrengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providersCloudflare
 
Kentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS AttacksKentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS AttacksCloudflare
 
Stopping DDoS Attacks in North America
Stopping DDoS Attacks in North AmericaStopping DDoS Attacks in North America
Stopping DDoS Attacks in North AmericaCloudflare
 
It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?Cloudflare
 
Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)Cloudflare
 
Bring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teamsBring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teamsCloudflare
 
Accelerate your digital transformation
Accelerate your digital transformationAccelerate your digital transformation
Accelerate your digital transformationCloudflare
 

More from Cloudflare (20)

Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)
 
Close your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with CloudflareClose your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with Cloudflare
 
Why you should replace your d do s hardware appliance
Why you should replace your d do s hardware applianceWhy you should replace your d do s hardware appliance
Why you should replace your d do s hardware appliance
 
Don't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable WebinarDon't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable Webinar
 
Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021
 
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
 
Zero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fastZero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fast
 
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
 
Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...
 
Scaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-serviceScaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-service
 
Application layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare dataApplication layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare data
 
Recent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respondRecent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respond
 
Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)
 
Strengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providersStrengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providers
 
Kentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS AttacksKentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
 
Stopping DDoS Attacks in North America
Stopping DDoS Attacks in North AmericaStopping DDoS Attacks in North America
Stopping DDoS Attacks in North America
 
It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?
 
Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)
 
Bring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teamsBring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teams
 
Accelerate your digital transformation
Accelerate your digital transformationAccelerate your digital transformation
Accelerate your digital transformation
 

Recently uploaded

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Recently uploaded (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Go Memory

  • 1. Understanding Go Memory September 11, 2013 John Graham-Cumming www.cloudflare.com!
  • 2. Allocation Primitives •  new(T)! •  Allocates memory for item with type T! •  Zeroes it zeroed ret = runtime·mallocgc(typ->size, flag, 1, 1);! ! •  make(T)! •  Allocates memory for item with type T! •  Initializes it •  Needed for channels, maps and slices •  Memory comes from internal heap www.cloudflare.com!
  • 3. Two memory freeing processes •  Garbage collection •  Determines which blocks of memory are no longer used •  Marks areas of heap so they can be reused by your program •  Scavenging •  Determines when parts of the heap are idle for a long time •  Returns memory to the operation system www.cloudflare.com!
  • 4. Garbage collection •  Controlled by the GOGC environment variable •  And by debug.SetGCPercentage()! // Initialized from $GOGC. GOGC=off means no gc.! //! // Next gc is after we've allocated an extra amount of! // memory proportional to the amount already in use.! // If gcpercent=100 and we're using 4M, we'll gc again! // when we get to 8M. This keeps the gc cost in linear! // proportion to the allocation cost. Adjusting gcpercent! // just changes the linear constant (and also the amount of! // extra memory used).! •  Default is same as GOGC=100! •  Can set GOGC=off or debug.SetGCPercentage(-1) (no garbage collection at all) www.cloudflare.com!
  • 5. Scavenging •  Runs once per minute // If we go two minutes without a garbage collection, ! // force one to run.! forcegc = 2*60*1e9;! ! // If a span goes unused for 5 minutes after a garbage! // collection, we hand it back to the operating system.! limit = 5*60*1e9;! •  Can also force return of all unused memory by calling debug.FreeOSMemory()! www.cloudflare.com!
  • 6. Memory Statistics •  Read with runtime.ReadMemStats(&m)
 ! •  The MemStats struct has tons of members •  Useful ones for looking at heap •  HeapInuse - # bytes in the heap allocated to things •  HeapIdle - # bytes in heap waiting to be used •  HeapSys - # bytes obtained from OS •  HeapReleased - # bytes released to OS www.cloudflare.com!
  • 7. Test garbage making program func makeBuffer() []byte { ! return make([]byte, rand.Intn(5000000)+5000000) }! ! func main() { ! pool := make([][]byte, 20)! ! makes := 0 ! for { ! b := makeBuffer()
 makes += 1! ! i := rand.Intn(len(pool))! pool[i] = b! ! time.Sleep(time.Second)! }! }! www.cloudflare.com! !
  • 10. Use a buffered channel func main() {! pool := make([][]byte, 20)! idle:= make(chan []byte, 5)! ! makes := 0! for {! var b []byte! select {! case b = <-idle:! default:! makes += 1! b = makeBuffer()! }! ! ! ! ! i := rand.Intn(len(pool))! if pool[i] != nil {! select {! case idle<- pool[i]:! pool[i] = nil! default:! }! }! pool[i] = b! time.Sleep(time.Second)! }! } www.cloudflare.com!
  • 11. select for non-blocking receive A buffered channel makes a simple queue idle:= make(chan []byte, 5)! ! select {! case b = <-idle:
 ! default:! Try to get from the makes += 1! idle queue b = makeBuffer()! }! Idle queue empty? Make a new buffer www.cloudflare.com!
  • 12. select for non-blocking send A buffered channel makes a simple queue idle:= make(chan []byte, 5)! ! select {! case buffer <- pool[i]:! pool[i] = nil! ! Try to return buffer default:! to the idle queue }! Idle queue full? GC will have to deal with the buffer www.cloudflare.com!
  • 14. More realistic: 20 goroutines func main() {! pool := make([][]byte, 200)! ! for i := 0; i < 10; i++ {! go func(offset int) {! for {! b := makeBuffer()! j := offset+rand.Intn(20)! pool[j] = b! ! time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))! }! }(i*20)! }! }! www.cloudflare.com!
  • 16. Shared across goroutines func main() {! buffer := make(chan []byte, 5)! ! pool := make([][]byte, 200)! for i := 0; i < 10; i++ {! go func(offset int) {! for {! var b []byte! select {! case b = <-buffer:! default: b = makeBuffer()! }! j := offset+rand.Intn(20)! if pool[j] != nil {! select {! case buffer <- pool[j]: pool[j] = nil! default:! }! }! pool[j] = b! time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000))! }! }(i*20)! }! ! www.cloudflare.com!
  • 18. More realistic example •  Alter code to •  Always try to give back a random buffer from the pool •  50% of the time get a new one •  Should create more garbage www.cloudflare.com!
  • 22. Also •  This works for things other than []byte •  Can be done with arbitrary types •  Just need some way to reset •  There’s a proposal to add something like this to the Go package library •  sync.Cache •  Follow TODO www.cloudflare.com!