Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 155 additions & 38 deletions gocache/awscache/blobserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,50 @@ const (
fillTimeout = time.Minute

// maxFills is the maximum number of fills in progress.
maxFills = 64
//
// The estimates below use blob sizes and request rates from production (as
// of 2026-11-24), measured S3 latencies, and i7i.xlarge nodes:
//
// - About half of the blobs that clients read are 64 KiB or less, 95%
// are 1 MiB or less, and the largest are 64 MiB. The mean is about
// 370 KiB of lz4.
// - The mean S3 first byte is about 31 ms (p95 76 ms), and the mean
// transfer is about 4 ms. Thus the mean fill takes about 35 ms.
// - So each fill slot does about 29 fills/s, or about 11 MB/s.
//
// Thus the peak rate of fills is approximately:
//
// maxFills S3 GETs/s throughput
// 64 1,800 0.7 GB/s (5.5 Gbps)
// 128 3,700 1.4 GB/s (11 Gbps)
// 256 7,300 2.8 GB/s (22 Gbps)
//
// If all fills take as long as the p95 first byte, the rates are a
// little less than half.
//
// At peak, cigocached serves about 2,200 blob GETs/s and about 550 blob
// writes/s. Each write causes a fill, so there are at most about 2,700
// fills/s even if all GETs miss, and 128 is sufficient. It also:
//
// - Is about the number of fills that the network of the node can
// keep busy. An i7i.xlarge bursts to 10 Gbps, or about 3,300
// fills/s, and its baseline is 2.3 Gbps, or about 800 fills/s. More
// fills only share the network, so each fill is slower, which makes
// GETs that wait for a fill slower, and makes large blobs exceed
// fillTimeout.
// - Keeps the connections to S3 below the MaxIdleConnsPerHost (256)
// that awscache sets on the AWS HTTP transport, so the fills use
// the same connections again and don't open new ones.
// - Keeps the rate of S3 GETs below the 5,500 GETs/s that one S3
// prefix partition supports, which decreases the risk of 503
// SlowDown errors. Clients also get blobs from S3 directly when
// they miss, so if all GETs miss, the total is about 4,900 GETs/s.
maxFills = 128

// defaultMaxQueued is the maximum number of queued blob fills after
// maxFills. The cache is very bursty, so the queue is always expected to
// drain in quiet periods, but this limit ensures it can't grow unbounded.
defaultMaxQueued = 1_000_000

// relatime is how old the modification time of a blob's file can be
// before a GET of the blob updates it. A new Server uses these times to
Expand All @@ -77,11 +120,12 @@ const (
)

var (
errCached = errors.New("blob is already cached")
errFilling = errors.New("a fill of the blob is in progress")
errLoading = errors.New("server is finding the blobs on disk")
errBusy = errors.New("too many fills in progress")
errBlobTooLarge = errors.New("blob is larger than the cache")
errCached = errors.New("blob is already cached")
errFilling = errors.New("a fill of the blob is in progress")
errQueued = errors.New("a fill of the blob is in the queue")
errServerLoading = errors.New("server is finding the blobs on disk")
errBusy = errors.New("the queue of fills is full")
errBlobTooLarge = errors.New("blob is larger than the cache")
)

// Option is an optional setting for [New].
Expand All @@ -92,6 +136,7 @@ type options struct {
awsConfig *aws.Config
blobPrefix string
get getFunc
maxQueued int
}

// getFunc opens the blob sha in S3 and returns its size. It returns
Expand Down Expand Up @@ -132,23 +177,34 @@ func withGetter(get getFunc) Option {
}
}

// withMaxQueued sets the maximum number of blobs in the queue of fills, for
// tests.
func withMaxQueued(n int) Option {
return func(o *options) {
o.maxQueued = n
}
}

// Server is a caching HTTP server for blobs that are durably stored in S3.
// It is a latency optimization, so that blobs too big to be inlined in
// DynamoDB (> 700 bytes) can still be served at low latencies. Use [New] to
// make one.
type Server struct {
dir string
maxBytes int64
logf logger.Logf
get getFunc
s3blobs *awscache.S3Blobs // nil in tests
m *serverMetrics
loaded chan struct{} // closed when the blobs on disk are in ll
dir string
maxBytes int64
maxQueued int
logf logger.Logf
get getFunc
s3blobs *awscache.S3Blobs // nil in tests
m *serverMetrics
loaded chan struct{} // closed when the blobs on disk are in ll

mu sync.Mutex
ll *list.List
ents map[string]*list.Element
filling map[string]*fill // blobs with a fill in progress
queue *list.List // SHAs of blobs that wait for a fill, oldest at the front
queued map[string]bool // SHAs in queue
usage int64
reserved int64
}
Expand All @@ -173,20 +229,24 @@ func New(ctx context.Context, bucket, dir string, maxBytes int64, opts ...Option
return nil, errors.New("blobserver: Server needs a dir and a positive maxBytes")
}
o := options{
logf: log.Printf,
logf: log.Printf,
maxQueued: defaultMaxQueued,
}
for _, opt := range opts {
opt(&o)
}
s := &Server{
dir: dir,
maxBytes: maxBytes,
logf: logger.Logf(tslogger.RateLimitedFn(tslogger.Logf(o.logf), time.Minute, 5, 100)),
get: o.get,
loaded: make(chan struct{}),
ll: list.New(),
ents: make(map[string]*list.Element),
filling: make(map[string]*fill),
dir: dir,
maxBytes: maxBytes,
maxQueued: o.maxQueued,
logf: logger.Logf(tslogger.RateLimitedFn(tslogger.Logf(o.logf), time.Minute, 5, 100)),
get: o.get,
loaded: make(chan struct{}),
ll: list.New(),
ents: make(map[string]*list.Element),
filling: make(map[string]*fill),
queue: list.New(),
queued: make(map[string]bool),
}
s.m = newServerMetrics(s)
if s.get == nil {
Expand Down Expand Up @@ -268,19 +328,43 @@ func (s *Server) touch(sha string, mtime time.Time) {

// beginFill records the start of a fill of the blob sha. It returns
// errCached if the blob is on disk, errFilling if a fill of the blob is in
// progress, and errLoading or errBusy if the server can't start a fill now.
// If it returns a fill, the caller must call endFill.
// progress, and errServerLoading if the server can't start a fill now. If the
// maximum number of fills are in progress, beginFill puts the blob in the
// queue of fills and returns errQueued, or it returns errBusy if the queue is
// full. If it returns a fill, the caller must call endFill.
func (s *Server) beginFill(sha string) (*fill, error) {
select {
case <-s.loaded:
default:
return nil, errLoading
return nil, errServerLoading
}
s.mu.Lock()
defer s.mu.Unlock()
if err := s.canFillLocked(sha); err != nil {
return nil, err
}
if s.queued[sha] {
return nil, errQueued
}
if len(s.filling) >= maxFills {
if s.queue.Len() >= s.maxQueued {
return nil, errBusy
}
s.queue.PushBack(sha)
s.queued[sha] = true
return nil, errQueued
}
return s.addFillLocked(sha), nil
}

// canFillLocked returns errCached if the blob sha is on disk, and errFilling
// if a fill of the blob is in progress. If the blob is in the LRU list but
// its file isn't on disk, canFillLocked removes the blob from the list.
// s.mu must be held.
func (s *Server) canFillLocked(sha string) error {
if e, ok := s.ents[sha]; ok {
if _, err := os.Stat(s.path(sha)); !os.IsNotExist(err) {
return nil, errCached
return errCached
}
// The blob is in the list, but its file isn't on disk. This occurs
// if an eviction of an earlier copy of the blob removes the file
Expand All @@ -291,24 +375,43 @@ func (s *Server) beginFill(sha string) (*fill, error) {
s.usage -= e.Value.(*blobFile).size
}
if s.filling[sha] != nil {
return nil, errFilling
}
if len(s.filling) >= maxFills {
return nil, errBusy
return errFilling
}
return nil
}

// addFillLocked records the start of a fill of the blob sha. s.mu must be
// held.
func (s *Server) addFillLocked(sha string) *fill {
f := &fill{
size: -1,
done: make(chan struct{}),
}
s.filling[sha] = f
return f, nil
return f
}

func (s *Server) endFill(sha string, f *fill) {
// endFill records the end of the fill f of the blob sha. Then it removes
// blobs from the front of the queue of fills until it finds one that it can
// fill. It records the start of the fill of that blob, and returns its SHA
// and fill. The caller must call endFill for that fill. If the queue has no
// blob to fill, endFill returns a nil fill.
func (s *Server) endFill(sha string, f *fill) (nextSHA string, next *fill) {
s.mu.Lock()
delete(s.filling, sha)
for next == nil && s.queue.Len() > 0 {
nextSHA = s.queue.Remove(s.queue.Front()).(string)
delete(s.queued, nextSHA)
if s.canFillLocked(nextSHA) == nil {
next = s.addFillLocked(nextSHA)
}
}
s.mu.Unlock()
close(f.done)
if next == nil {
return "", nil
}
return nextSHA, next
}

// fillSize returns the size of the blob sha that a fill in progress is
Expand Down Expand Up @@ -491,13 +594,20 @@ func (s *Server) startFill(sha string) error {
if err != nil {
return err
}
go func() {
defer s.endFill(sha, f)
go s.runFills(sha, f)
return nil
}

// runFills does the fill f of the blob sha. Then it does the fills from the
// queue of fills that [Server.endFill] returns, until the queue is empty.
// When busy, there may be up to [maxFills] goroutines running this function.
func (s *Server) runFills(sha string, f *fill) {
for f != nil {
start := time.Now()
result := s.fillFromS3(sha)
s.m.fills.WithLabelValues(result).Observe(time.Since(start).Seconds())
}()
return nil
sha, f = s.endFill(sha, f)
}
}

// fillFromS3 gets the blob sha from S3 and stores it. It returns the result
Expand Down Expand Up @@ -534,7 +644,9 @@ func (s *Server) serveWarm(w http.ResponseWriter, sha string) {
result = "cached"
case errors.Is(err, errFilling):
result = "filling"
case errors.Is(err, errLoading):
case errors.Is(err, errQueued):
result = "queued"
case errors.Is(err, errServerLoading):
result = "loading"
case errors.Is(err, errBusy):
result = "busy"
Expand Down Expand Up @@ -609,6 +721,7 @@ func (s *Server) Collectors() []prometheus.Collector {
s.m.maxBytes,
s.m.blobs,
s.m.fillsInProgress,
s.m.fillsQueued,
}
if s.s3blobs != nil {
cs = append(cs, s.s3blobs.Collectors()...)
Expand All @@ -628,6 +741,7 @@ type serverMetrics struct {
maxBytes prometheus.GaugeFunc
blobs prometheus.GaugeFunc
fillsInProgress prometheus.GaugeFunc
fillsQueued prometheus.GaugeFunc
}

func newServerMetrics(s *Server) *serverMetrics {
Expand All @@ -653,7 +767,7 @@ func newServerMetrics(s *Server) *serverMetrics {
}, []string{"result"}),
warms: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "gocache_blobserver_warms_total",
Help: "blob POST requests, labeled by result: started (a fill started), cached (already on disk), filling (a fill of the blob in progress), loading (finding the blobs on disk), or busy (too many fills in progress)",
Help: "blob POST requests, labeled by result: started (a fill started), cached (already on disk), filling (a fill of the blob in progress), queued (the blob is in the queue of fills), loading (finding the blobs on disk), or busy (the queue of fills is full)",
}, []string{"result"}),
servedBytes: prometheus.NewCounter(prometheus.CounterOpts{
Name: "gocache_blobserver_served_bytes_total",
Expand Down Expand Up @@ -683,5 +797,8 @@ func newServerMetrics(s *Server) *serverMetrics {
fillsInProgress: gauge("gocache_blobserver_fills_in_progress", "fills from S3 in progress", func() int64 {
return int64(len(s.filling))
}),
fillsQueued: gauge("gocache_blobserver_fills_queued", "blobs in the queue of fills that wait for a fill in progress to end", func() int64 {
return int64(s.queue.Len())
}),
}
}
Loading
Loading