go
45 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package cache
import (
"context"
"sync/atomic"
"time"
)
type Snapshot map[string]string
type Store struct {
p atomic.Pointer[Snapshot]
load func(context.Context) (Snapshot, error)
}
func New(load func(context.Context) (Snapshot, error)) *Store {
s := &Store{load: load}
empty := Snapshot{}
s.p.Store(&empty)
return s
}
func (s *Store) Get(k string) (string, bool) {
snap := s.p.Load()
v, ok := (*snap)[k]
return v, ok
}
func (s *Store) Run(ctx context.Context, every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
c, cancel := context.WithTimeout(ctx, 2*time.Second)
snap, err := s.load(c)
cancel()
if err == nil {
s.p.Store(&snap)
}
}
}
}
1 file · go
Explain with highlit
I often need a fast read path for small datasets (like a list of active plans or an allowlist) that updates periodically. Instead of locking on every read, I store a pointer to an immutable snapshot in atomic.Pointer. Reads are lock-free and safe; refresh happens in the background and swaps the pointer atomically. The key is immutability: never modify the map in place after publishing it, or you’ll race. I also make refresh honor context.Context and timeouts, and I keep the last good value if refresh fails. In production, this pattern keeps latency stable under load because readers never contend on mutexes. It’s a good fit when data changes slowly and correctness matters more than immediate consistency.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
typescript
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
typescript
reliability
retry
by codesnips
2 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
rust
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
rust
concurrency
lock-free
by Marcus Chen
1 tab
javascript
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
javascript
promises
async-await
by Alex Chang
1 tab
rust
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
rust
concurrency
channels
by Marcus Chen
1 tab
Share this code
Here's the card — post it anywhere.