Skip to content
Package47 repository health

go-cache

A thread-safe, in-memory key-value cache for Go with per-item expiration, atomic counters, and optional disk persistence.

Library Govv2.1.0+incompatible8,841 stars MIT License
go get github.com/patrickmn/go-cache
View source

Repository health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
Fair
  • Development activity0
  • Maintenance20
  • Community68
  • Maturity60
  • Momentum40

Technical analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
Good
  • Architecture80
  • Code quality78
  • Innovation55
  • Learning curve85

go-cache is a thread-safe, in-memory key-value store for Go, built around a simple map[string]interface{} guarded by a sync.RWMutex, with per-item expiration times. It behaves like a single-process Memcached: any Go value can be cached forever or for a set duration without the overhead of serializing data or making network round-trips to an external cache server.

Expired items are automatically purged by a background janitor goroutine on a configurable interval, and the entire cache can be saved to and restored from disk using gob encoding — useful for surviving short-lived restarts without a cold cache. An experimental sharded cache implementation is also included (unexported, opt-in via the package’s internal APIs) for workloads that need finer-grained locking than the single-mutex default.

What You Get

  • A generic Cache type usable with any Go value via interface{}, with Set/Get/GetWithExpiration/Delete and typed Increment/Decrement helpers for every numeric kind.
  • Configurable default expiration and cleanup interval, set once at construction time with New() or NewFrom().
  • Optional persistence to disk (or any io.Writer) via gob encoding through Save/SaveFile and Load/LoadFile.
  • An OnEvicted callback hook fired on delete or expiry, plus an experimental sharded cache variant for high-concurrency scenarios.

Common Use Cases

  • Caching expensive computed responses or database query results in a single-process API service without standing up Redis or Memcached.
  • Tracking per-key counters (rate limits, request counts) with Increment/IncrementInt and an expiration window that resets automatically.
  • Storing short-lived session data or parsed auth tokens with expirations that mirror the token’s own TTL.
  • Persisting a long-running worker’s in-memory cache to disk with SaveFile so it can reload with LoadFile after a deploy or crash.

Under The Hood

Architecture

The package is a single cache package split across two files: cache.go holds the primary implementation and sharded.go an experimental, currently-unexported sharded variant. The public Cache type wraps an internal *cache struct purely so runtime.SetFinalizer can stop the background janitor goroutine when the wrapper is garbage-collected — a deliberate embedding trick called out directly in the source comments. All state lives behind a single sync.RWMutex; read paths (Get, GetWithExpiration) take a read lock and inline the expiration check to avoid an extra function call, while writes (Set, Add, Replace, the typed Increment*/Decrement* family) take the write lock. The sharded variant in sharded.go distributes keys across N independent *cache buckets chosen by a custom djb33 hash, so a change to the core cache struct’s locking model would also need to stay consistent with the sharded bucket type it embeds.

Tech Stack

Zero third-party dependencies — the entire implementation uses only the Go standard library: sync for locking, time for expiration arithmetic, encoding/gob for persistence, crypto/rand/math/big (with an insecurerand fallback) for the sharded cache’s hash seed, and runtime/os for the finalizer and CSPRNG-failure warning. There is no go.mod in the repository; the module is published under the legacy pre-Go-modules convention, reflected in its +incompatible version tag, and consumers import it as a plain GOPATH-style package.

Code Quality

cache_test.go contains 72 test functions covering the base cache, expiration timing, NewFrom round-tripping, pointer storage, and every typed Increment*/Decrement* variant (int8 through uint64 and both float sizes), plus 19 benchmark functions comparing locked vs. sharded performance; sharded_test.go adds a further concurrency-focused test. Error handling is explicit and idiomatic — Add/Replace/typed increments return a descriptive error rather than panicking or silently no-op’ing. Naming follows standard Go exported/unexported conventions throughout. No linter configuration, formatter config, or CI workflow file is present in the repository, and there is no go.mod, so the project predates (or opted out of) modern Go tooling conventions.

API Design The public surface mirrors familiar cache semantics (Set/Get/Delete, DefaultExpiration/NoExpiration sentinels) so it reads naturally to anyone who has used Memcached-style clients. The type-assertion burden inherent to a pre-generics interface{} value store is called out directly in the README with idiomatic patterns for consumers, and the typed IncrementInt64/IncrementFloat64-style helpers exist specifically to avoid a second type assertion after an atomic update — a small but genuinely convenience-focused API decision rather than a generic wrapper.

Used by 16 apps in this directory

Every app whose dependencies include github.com/patrickmn/go-cache, nine to a page.

Showing 16 apps
Go 73%GPL 3.0

1Panel

37,480

Devops · Hosting Control Panel · Monitoring

The only open-source VPS control panel with native AI agent runtime — deploy websites, Docker stacks, and local LLMs from one web interface.

App
Built with
  • Go 73%
  • Vue 27%
Updated yesterdayView details
Go 58%Apache 2.0

Authgear

2,158

Authentication

Open-source, self-hostable authentication platform with passkeys, biometric login, SSO, MFA, and GraphQL admin API — a full Auth0/Clerk/Firebase alternative for SaaS and mobile apps.

App
Built with
  • Go 58%
  • HTML 20%
  • TypeScript 19%
Updated yesterdayView details
Go 90%Apache 2.0

CasaOS

37,681

File Storage · Hosting Control Panel

Your simple, elegant personal cloud OS for home data and apps

App
Built with
  • Go 90%
Updated 4 days agoView details
Go 36%Apache 2.0

CubeSandbox

13,391

AI Agents · Developer Tools · Security

Instant, concurrent, hardware-isolated MicroVM sandboxes for AI agents — E2B-API compatible, sub-60ms cold starts, and a built-in zero-trust egress proxy, all self-hostable at scale.

App
Built with
  • Go 36%
  • Rust 23%
  • C 20%
Updated todayView details
Go 39%MIT

ezBookkeeping

6,104

Invoicing Finance

Lightweight self-hosted personal finance manager with AI receipt scanning, multi-currency support, and MCP integration for complete data privacy.

App
Built with
  • Go 39%
  • Vue 32%
  • TypeScript 25%
Updated todayView details
Go 67%AGPL 3.0

Fider

4,632

Customer Support · Product Management

Open-source feedback portal where customers submit, vote on, and track feature requests so product teams build what actually matters.

App
Built with
  • Go 67%
  • TypeScript 27%
Updated 2 days agoView details
Go 51%AGPL 3.0

Filestash

14,922

File Storage

A self-hosted file management platform that unifies access to S3, SFTP, SMB, FTP, WebDAV, NFS, Git, SharePoint, and 20+ other storage backends through a single extensible web interface.

App
Built with
  • Go 51%
  • JavaScript 35%
Updated 3 days agoView details
TypeScript 47%AGPL 3.0

Grafana

78,021

Analytics · Monitoring

The open-source observability platform that unifies metrics, logs, and traces from any data source into dynamic, queryable dashboards.

App
Built with
  • TypeScript 47%
  • Go 47%
Updated todayView details
TypeScript 99%MIT

GraphQL Hive

481

Developer Tools · Devops · Monitoring

Open-source GraphQL schema registry and observability platform with breaking change detection, federation support, and CI/CD integration for teams of any size.

App
Built with
  • TypeScript 99%
Updated yesterdayView details

Join founders building with open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on SubstackJoin 750+ subscribers