Skip to content

Cache ​

Cache the photo list when repeated reads would otherwise run the same SQLite query. Keep the records in SQLite so the app can rebuild the list after a cache miss or restart.

When to Use Cache ​

Use cache for data you can reload or recompute, such as derived summaries, short-lived lookups, session state, and rate limit counters. A cache value can disappear at any time. Coordination locks also need an explicit expiry and a plan for work that outlives the lock.

Start with memory cache for one-process development. API, worker, and scheduler processes each have their own memory cache, even on the same host.

Access Cache from Application Code ​

Start with Save and List Photos. Stop forj dev while you add the cache component to the existing render.components list in .goforj.yml. Preserve the other components, then run:

bash
forj render

In .env, select the local cache:

text
CACHE_SUPPORTED_DRIVERS=memory
CACHE_DRIVER=memory

internal/caches owns the default and named stores. Inject its manager into a service, then select the store in the constructor. The root app also exposes app.Cache() and app.Caches() for app-level composition.

Cache-Aside Shape ​

In internal/photos/service.go, import github.com/goforj/cache and your generated internal/caches package. Add the cache field and constructor argument. If you added other dependencies to Service, keep them alongside the cache.

go
// Service saves photo records and caches their list for up to 30 seconds.
type Service struct {
	repo  *PhotoRepo
	cache *cache.Cache
}

// NewService selects the default cache configured for this app.
func NewService(repo *PhotoRepo, manager *caches.Manager) *Service {
	return &Service{repo: repo, cache: manager.Default()}
}

Rename the existing ListNewest method and its comment to listNewest. Add this wrapper so callers keep using ListNewest and SQLite is queried on a cache miss.

go
// ListNewest permits a cached list to remain stale for up to 30 seconds.
func (s *Service) ListNewest(ctx context.Context) ([]Summary, error) {
	return cache.Remember(s.cache.WithContext(ctx), "photos:list:v1", 30*time.Second,
		func() ([]Summary, error) {
			return s.listNewest(ctx)
		})
}

The existing photos.NewService registration in app/wire/inject_services_app.go stays in place. Run forj build to regenerate its wiring, then start forj dev.

The first GET /api/v1/photos loads SQLite and caches the result. Later requests reuse the list until its 30-second TTL expires. Saving a photo still writes directly to SQLite. This example accepts a stale list for up to 30 seconds after a write.

Expiration and Invalidation ​

If your workflow needs a fresher list, delete photos:list:v1 after a successful database commit with s.cache.WithContext(ctx).Delete("photos:list:v1"). Handle deletion errors separately from the committed write so clients do not retry a successful save as though it failed.

Deletion and the database commit are separate operations. A concurrent reader can load old rows before the commit and refill the cache after deletion. Use a stronger coordination strategy when stale results are unacceptable. Keep the TTL as a limit on staleness, and change the key version when the cached representation changes.

The example returns cache read and write errors to the caller through cache.Remember. If you choose to serve database results during cache outages, implement and test that fallback explicitly.

Verify Cache Behavior ​

With forj dev running, use a second terminal to populate the cache:

bash
curl http://localhost:3000/api/v1/photos

Expect the saved photo list from SQLite. Save another record using the POST request in Save and List Photos, then repeat the GET immediately. The list can still show the previous result. Repeat it after 30 seconds to see the new record.

In a focused memory-cache test, count repository loads to prove that a miss loads once, a hit skips the repository, and expiry or deletion loads again. Test repository failures and cache failures separately. HTTP output alone does not establish how many database queries ran.

Choosing Cache Drivers ​

NeedDriver choice
One-process development and focused testsmemory
Local cache files that survive a process restartfile
Shared values across API, workers, or hostsRedis, Memcached, NATS, DynamoDB, or SQL-backed cache
Shared locks or rate limitsA backend that supports the required operation, with explicit TTLs

CACHE_SUPPORTED_DRIVERS selects the drivers compiled into the binary. CACHE_DRIVER selects the default store at runtime. Named settings add named accessors after forj build:

text
CACHE_SUPPORTED_DRIVERS=memory,redis
CACHE_DRIVER=memory
CACHE_SESSIONS_DRIVER=redis

This creates app.Caches().Sessions(). Configure its connection using the cache environment reference. During forj dev, an app listed in dev.apps rebuilds after environment changes. See Generation Commands for focused generation workflows.

Cache Shell ​

Inspect Redis stores with forj cache, the alias for the app's cache:shell command. Select a named store with its app-facing name:

bash
forj cache
forj cache sessions
forj cache --store sessions

GoForj tries redis-cli locally, then the generated Docker Compose redis service when available. Select a method or print the command to inspect it:

bash
forj cache --method local
forj cache --method compose
forj cache --print

Run a command without an interactive shell, or pass native redis-cli arguments after --:

bash
forj cache --exec "PING"
# PONG
forj cache sessions --exec "PING"
# PONG
forj cache -- PING
# PONG
forj cache sessions -- GET user:1

Local and Production Drivers ​

Choose a shared backend when several processes need the same values. Persistence in a cache backend does not make cached data the source of truth. Check the cache library reference for supported operations and driver limits.

Before releasing a Redis deployment, run ./bin/app cache:shell --exec "PING" against the deployed configuration. Expect PONG. For a named store, add --store sessions. This verifies connectivity, while TTL, invalidation, and fallback behavior still need service tests.

In a split deployment, exercise the cache workflow through every API, worker, or scheduler process that depends on it. Check readiness after startup. An API probe does not establish that a separate worker has the same credentials or network access.

Next Steps ​