• Stars
    star
    424
  • Rank 98,805 (Top 2 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Clone of golang/groupcache with TTL and Item Removal support

groupcache

A modified version of group cache with support for context.Context, go modules, and explicit key removal and expiration. See the CHANGELOG for a complete list of modifications.

Summary

groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases.

For API docs and examples, see http://godoc.org/github.com/mailgun/groupcache/v2

Modifications from original library

  • Support for explicit key removal from a group. Remove() requests are first sent to the peer who owns the key, then the remove request is forwarded to every peer in the groupcache. NOTE: This is a best case design since it is possible a temporary network disruption could occur resulting in remove requests never making it their peers. In practice this scenario is very rare and the system remains very consistent. In case of an inconsistency placing a expiration time on your values will ensure the cluster eventually becomes consistent again.

  • Support for expired values. SetBytes(), SetProto() and SetString() now accept an optional time.Time which represents a time in the future when the value will expire. If you don't want expiration, pass the zero value for time.Time (for instance, time.Time{}). Expiration is handled by the LRU Cache when a Get() on a key is requested. This means no network coordination of expired values is needed. However this does require that time on all nodes in the cluster is synchronized for consistent expiration of values.

  • Now always populating the hotcache. A more complex algorithm is unnecessary when the LRU cache will ensure the most used values remain in the cache. The evict code ensures the hotcache never overcrowds the maincache.

Comparing Groupcache to memcached

Like memcached, groupcache:

  • shards by key to select which peer is responsible for that key

Unlike memcached, groupcache:

  • does not require running a separate set of servers, thus massively reducing deployment/configuration pain. groupcache is a client library as well as a server. It connects to its own peers.

  • comes with a cache filling mechanism. Whereas memcached just says "Sorry, cache miss", often resulting in a thundering herd of database (or whatever) loads from an unbounded number of clients (which has resulted in several fun outages), groupcache coordinates cache fills such that only one load in one process of an entire replicated set of processes populates the cache, then multiplexes the loaded value to all callers.

  • does not support versioned values. If key "foo" is value "bar", key "foo" must always be "bar".

Loading process

In a nutshell, a groupcache lookup of Get("foo") looks like:

(On machine #5 of a set of N machines running the same code)

  1. Is the value of "foo" in local memory because it's super hot? If so, use it.

  2. Is the value of "foo" in local memory because peer #5 (the current peer) is the owner of it? If so, use it.

  3. Amongst all the peers in my set of N, am I the owner of the key "foo"? (e.g. does it consistent hash to 5?) If so, load it. If other callers come in, via the same process or via RPC requests from peers, they block waiting for the load to finish and get the same answer. If not, RPC to the peer that's the owner and get the answer. If the RPC fails, just load it locally (still with local dup suppression).

Example

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/mailgun/groupcache/v2"
)

func ExampleUsage() {

    // NOTE: It is important to pass the same peer `http://192.168.1.1:8080` to `NewHTTPPoolOpts`
    // which is provided to `pool.Set()` so the pool can identify which of the peers is our instance.
    // The pool will not operate correctly if it can't identify which peer is our instance.
    
    // Pool keeps track of peers in our cluster and identifies which peer owns a key.
    pool := groupcache.NewHTTPPoolOpts("http://192.168.1.1:8080", &groupcache.HTTPPoolOptions{})

    // Add more peers to the cluster You MUST Ensure our instance is included in this list else
    // determining who owns the key accross the cluster will not be consistent, and the pool won't
    // be able to determine if our instance owns the key.
    pool.Set("http://192.168.1.1:8080", "http://192.168.1.2:8080", "http://192.168.1.3:8080")

    server := http.Server{
        Addr:    "192.168.1.1:8080",
        Handler: pool,
    }

    // Start a HTTP server to listen for peer requests from the groupcache
    go func() {
        log.Printf("Serving....\n")
        if err := server.ListenAndServe(); err != nil {
            log.Fatal(err)
        }
    }()
    defer server.Shutdown(context.Background())

    // Create a new group cache with a max cache size of 3MB
    group := groupcache.NewGroup("users", 3000000, groupcache.GetterFunc(
        func(ctx context.Context, id string, dest groupcache.Sink) error {

            // Returns a protobuf struct `User`
            user, err := fetchUserFromMongo(ctx, id)
            if err != nil {
                return err
            }

            // Set the user in the groupcache to expire after 5 minutes
            return dest.SetProto(&user, time.Now().Add(time.Minute*5))
        },
    ))

    var user User

    ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)
    defer cancel()

    if err := group.Get(ctx, "12345", groupcache.ProtoSink(&user)); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("-- User --\n")
    fmt.Printf("Id: %s\n", user.Id)
    fmt.Printf("Name: %s\n", user.Name)
    fmt.Printf("Age: %d\n", user.Age)
    fmt.Printf("IsSuper: %t\n", user.IsSuper)

    // Remove the key from the groupcache
    if err := group.Remove(ctx, "12345"); err != nil {
        log.Fatal(err)
    }
}

Note

The call to groupcache.NewHTTPPoolOpts() is a bit misleading. NewHTTPPoolOpts() creates a new pool internally within the groupcache package where it is uitilized by any groups created. The pool returned is only a pointer to the internallly registered pool so the caller can update the peers in the pool as needed.

More Repositories

1

transactional-email-templates

Responsive transactional HTML email templates
HTML
6,820
star
2

godebug

DEPRECATED! https://github.com/derekparker/delve
Go
2,507
star
3

flanker

Python email address and Mime parsing library
Python
1,618
star
4

talon

Python
1,235
star
5

mailgun-php

Mailgun's Official SDK for PHP
PHP
1,078
star
6

gubernator

High Performance Rate Limiting MicroService and Library
Go
944
star
7

mailgun-js-boland

A simple Node.js helper module for Mailgun API.
JavaScript
896
star
8

kafka-pixy

gRPC/REST proxy for Kafka
Go
752
star
9

mailgun-go

Go library for sending mail with the Mailgun API.
Go
678
star
10

mailgun.js

Javascript SDK for Mailgun
TypeScript
501
star
11

mailgun-ruby

Mailgun's Official Ruby Library
Ruby
462
star
12

expiringdict

Dictionary with auto-expiring values for caching purposes.
Python
331
star
13

holster

A place to keep useful golang functions and small libraries
Go
277
star
14

validator-demo

Mailgun email address jquery validation plugin http://mailgun.github.io/validator-demo/
JavaScript
259
star
15

node-prelaunch

A Mailgun powered landing page to capture early sign ups
JavaScript
230
star
16

dnsq

DNS Query Tool
Python
107
star
17

documentation

Mailgun Documentation
CSS
79
star
18

scroll

Scroll is a lightweight library for building Go HTTP services at Mailgun.
Go
61
star
19

kafka-http

Kafka http endpoint
Scala
51
star
20

forge

email dataset for email signature parsing
51
star
21

wordpress-plugin

Mailgun's Wordpress Plugin
PHP
47
star
22

lemma

Mailgun Cryptographic Tools
Go
39
star
23

multibuf

Bytes buffer that implements seeking and partially persisting to disk
Go
37
star
24

ttlmap

In memory dictionary with TTLs
Go
22
star
25

frontend-best-practices

Guides for React and Javascript coding style and best practices
21
star
26

pong

Generates http servers that respond in predefined manner
Go
20
star
27

proxyproto

High performance implementation of V1 and V2 Proxy Protocol
Go
19
star
28

log

Go logging library used at Mailgun.
Go
19
star
29

mailgun-meteor-demo

Simple meteor-based emailer with geolocation and UA tracking
JavaScript
16
star
30

timetools

Go library with various time utilities used at Mailgun.
Go
11
star
31

mailgun-java

Java SDK for integrating with Mailgun
Java
11
star
32

pelican-protocol

In ancient Egypt the pelican was believed to possess the ability to prophesy safe passage in the underworld. Pelicans are ferocious eaters of fish.
Go
11
star
33

metrics

Go library for emitting metrics to StatsD.
Go
11
star
34

roman

Obtain, cache, and automatically reload TLS certificates from an ACME server
Go
10
star
35

sandra

Go library providing some convenience wrappers around gocql.
Go
10
star
36

iptools

Go library providing utilities for working with hosts' IP addresses.
Go
9
star
37

cfg

Go library for working with app's configuration files used at Mailgun.
Go
9
star
38

minheap

Slightly more user-friendly heap on top of containers/heap
Go
8
star
39

logrus-hooks

Go
8
star
40

pebblezgo

go example of the pebblez transport: protocol buffers over zeromq
Go
7
star
41

glogutils

Utils for working with google logging library
Go
7
star
42

pylemma

Mailgun Cryptographic Tools
Python
5
star
43

callqueue

Serialized call queues
Go
4
star
44

media

Logos and brand guidelines
4
star
45

sneakercopy

A tool for creating encrypted tar archives for transferring sensitive data.
Rust
4
star
46

scripts

Example scripts that show how to interact with the Mailgun API
Python
1
star
47

etcd3-slim

Thin wrapper around Etcd3 gRPC stubs
Python
1
star