Skip to content
Open
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
969 changes: 854 additions & 115 deletions deployment/grafana-dashboards/Redis-Caches.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class OrganizationAccessTokenValidationCache {
constructor() {
this.cache = new BentoCache({
default: 'organizationAccessTokenValidation',
plugins: [cacheMetricsPlugin('bentocache:organization-access-token-validation')],
plugins: [cacheMetricsPlugin('bentocache:organization-access-token-validation', ['memory'])],
stores: {
organizationAccessTokenValidation: bentostore().useL1Layer(
memoryDriver({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { sha256 } from '../../auth/lib/supertokens-at-home/crypto';
import { Logger } from '../../shared/providers/logger';
import { REDIS_INSTANCE, type Redis } from '../../shared/providers/redis';

const domainChallengeMetrics = createCacheMetrics('hive:oidcDomainChallenge');
const domainChallengeMetrics = createCacheMetrics('hive:oidcDomainChallenge', ['redis']);

const SharedOIDCIntegrationDomainFieldsModel = z.object({
id: z.uuid(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { redisDriver } from 'bentocache/drivers/redis';
import { Inject, Injectable, Scope } from 'graphql-modules';
import { PostgresDatabasePool } from '@hive/postgres';
import { AuthorizationPolicyStatement } from '../../auth/lib/authz';
import { cacheMetricsPlugin } from '../../shared/lib/bentocache-cache-metrics';
import { cacheMetricsPlugin, entryAgeSerializer } from '../../shared/lib/bentocache-cache-metrics';
import { Logger } from '../../shared/providers/logger';
import { REDIS_INSTANCE, type Redis } from '../../shared/providers/redis';
import { Groups } from './groups';
Expand Down Expand Up @@ -45,7 +45,12 @@ export class OrganizationAccessTokensCache {
) {
this.cache = new BentoCache({
default: 'organizationAccessTokens',
plugins: [cacheMetricsPlugin('bentocache:organization-access-tokens')],
plugins: [
cacheMetricsPlugin('bentocache:organization-access-tokens', ['memory', 'redis'], {
entryAge: true,
}),
],
serializer: entryAgeSerializer,
stores: {
organizationAccessTokens: bentostore()
.useL1Layer(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { REDIS_INSTANCE, type Redis } from '../../shared/providers/redis';
const RECENTLY_EVICTED_WINDOW_MS = 60 * 60 * 1000;

/** Shared cache metrics, labelled with the Redis key prefix of the snapshots. */
const cacheMetrics = createCacheMetrics('schema-explorer-snapshot');
const cacheMetrics = createCacheMetrics('schema-explorer-snapshot', ['memory', 'redis']);

const requests = new metrics.Counter({
name: 'api_schema_explorer_cache_requests_total',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,61 @@
import { BentoCache, bentostore } from 'bentocache';
import { memoryDriver } from 'bentocache/drivers/memory';
import { metrics } from '@hive/service-common';
import { cacheMetricsPlugin } from './bentocache-cache-metrics';
import { cacheMetricsPlugin, entryAgeSerializer } from './bentocache-cache-metrics';

async function counterValue(name: string, labels: Record<string, string>) {
const metric = await metrics.register.getSingleMetric(name)?.get();
return (
metric?.values.find(value =>
Object.entries(labels).every(([key, label]) => value.labels[key] === label),
)?.value ?? 0
);
return metric?.values.find(value =>
Object.entries(labels).every(([key, label]) => value.labels[key] === label),
)?.value;
}

async function entryAgeSum(feature: string, result: string) {
const metric = await metrics.register.getSingleMetric('hive_cache_entry_age_seconds')?.get();
return metric?.values.find(
value =>
'metricName' in value &&
value.metricName === 'hive_cache_entry_age_seconds_sum' &&
value.labels.feature === feature &&
value.labels.result === result,
)?.value;
}

test('records misses, writes and hits of a BentoCache in the shared cache metrics', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const feature = 'test:bentocache-cache-metrics';
const cache = new BentoCache({
default: 'store',
plugins: [cacheMetricsPlugin(feature)],
plugins: [cacheMetricsPlugin(feature, ['memory'], { entryAge: true })],
serializer: entryAgeSerializer,
grace: '1h',
stores: { store: bentostore().useL1Layer(memoryDriver({ maxItems: 10 })) },
});

await cache.getOrSet({ key: 'a', factory: () => 1 });
await cache.getOrSet({ key: 'a', factory: () => 1 });
await cache.getOrSet({ key: 'a', factory: () => 1 });
await expect(
counterValue('hive_cache_requests_total', { feature, result: 'hit', layer: 'memory' }),
).resolves.toBe(0);
await expect(entryAgeSum(feature, 'graced_hit')).resolves.toBe(0);

await cache.getOrSet({ key: 'a', factory: () => ({ id: 1 }) });
vi.advanceTimersByTime(10_000);
await cache.getOrSet({ key: 'a', factory: () => ({ id: 1 }) });
await cache.getOrSet({ key: 'a', factory: () => ({ id: 1 }) });

expect(await counterValue('hive_cache_requests_total', { feature, result: 'miss' })).toBe(1);
expect(await counterValue('hive_cache_writes_total', { feature })).toBe(1);
expect(
await counterValue('hive_cache_requests_total', { feature, result: 'hit', layer: 'memory' }),
).toBe(2);
await expect(entryAgeSum(feature, 'hit')).resolves.toBe(20);

await cache.expire({ key: 'a' });
vi.advanceTimersByTime(5_000);
await cache.getOrSet({ key: 'a', factory: () => ({ id: 1 }) });

await expect(
counterValue('hive_cache_requests_total', { feature, result: 'graced_hit', layer: '' }),
).resolves.toBe(1);
await expect(entryAgeSum(feature, 'graced_hit')).resolves.toBe(15);
vi.useRealTimers();
});
Original file line number Diff line number Diff line change
@@ -1,22 +1,50 @@
import type { BentoCachePlugin } from 'bentocache/types';
import { createCacheMetrics } from '@hive/service-common';
import type { BentoCachePlugin, CacheSerializer } from 'bentocache/types';
import { createCacheMetrics, type CacheLayer } from '@hive/service-common';

const createdAtByValue = new WeakMap<object, number>();

/**
* BentoCache does not pass an entry's creation time to its hit event, so this serializer notes it
* for each entry read from a driver, keyed by the value the hit event then carries.
* Only object values are tracked.
*/
export const entryAgeSerializer: CacheSerializer = {
serialize: value => JSON.stringify(value),
deserialize(raw) {
const entry = JSON.parse(raw);
if (typeof entry?.createdAt === 'number' && entry.value && typeof entry.value === 'object') {
createdAtByValue.set(entry.value, entry.createdAt);
}
return entry;
},
};

function entryAgeSeconds(value: unknown) {
const createdAt = value && typeof value === 'object' ? createdAtByValue.get(value) : undefined;
return createdAt === undefined ? undefined : (Date.now() - createdAt) / 1000;
}

/**
* Records the hits, misses and writes of a BentoCache instance in the shared
* `hive_cache_requests_total` and `hive_cache_writes_total` metrics.
* `feature` should be the Redis key prefix of the cache's L2 layer.
* Entry ages are recorded when `entryAge` is set and the BentoCache uses `entryAgeSerializer`.
*/
export function cacheMetricsPlugin(feature: string): BentoCachePlugin {
const metrics = createCacheMetrics(feature);
export function cacheMetricsPlugin(
feature: string,
layers: CacheLayer[],
options: { entryAge?: boolean } = {},
): BentoCachePlugin {
const metrics = createCacheMetrics(feature, layers, options);

return {
register(bentocache) {
bentocache.on('cache:hit', event => {
const layer = event.layer === 'l1' ? 'memory' : 'redis';
const ageSeconds = entryAgeSeconds(event.value);
if (event.graced) {
metrics.gracedHit(layer);
metrics.gracedHit(ageSeconds);
} else {
metrics.hit(layer);
metrics.hit(event.layer === 'l1' ? 'memory' : 'redis', ageSeconds);
}
});
bentocache.on('cache:miss', () => metrics.miss());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class DistributedCache {
*/
ttlSeconds: number;
}): Promise<T> {
const metrics = createCacheMetrics(feature);
const metrics = createCacheMetrics(feature, ['redis']);
const redisKey = `${feature}:${key}`;
const cached = await this.get<T>(redisKey);
if (cached) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ export abstract class EphemeralStateStore<TModel extends z.ZodType> {
const state = randomBytes(32).toString('hex');
const key = `${this.keyPrefix}:${sha256(state)}`;
await this.redis.set(key, JSON.stringify(this.model.parse(data)), 'EX', 60 * 5);
createCacheMetrics(this.keyPrefix).write();
createCacheMetrics(this.keyPrefix, ['redis']).write();

return state;
}

async get(state: string): Promise<z.output<TModel> | null> {
const key = `${this.keyPrefix}:${sha256(state)}`;
const encodedData = await this.redis.getdel(key);
const metrics = createCacheMetrics(this.keyPrefix);
const metrics = createCacheMetrics(this.keyPrefix, ['redis']);
if (!encodedData) {
// Unknown, expired or already used state.
metrics.miss();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { redisDriver } from 'bentocache/drivers/redis';
import { Inject, Injectable, Scope } from 'graphql-modules';
import type { Target } from '../../../shared/entities';
import { isUUID } from '../../../shared/is-uuid';
import { cacheMetricsPlugin } from '../../shared/lib/bentocache-cache-metrics';
import { cacheMetricsPlugin, entryAgeSerializer } from '../../shared/lib/bentocache-cache-metrics';
import { REDIS_INSTANCE, type Redis } from '../../shared/providers/redis';
import { TargetStore } from './target-store';

Expand All @@ -24,7 +24,10 @@ export class TargetsByIdCache {
) {
this.cache = new BentoCache({
default: 'targetsById',
plugins: [cacheMetricsPlugin('bentocache:targetsById')],
plugins: [
cacheMetricsPlugin('bentocache:targetsById', ['memory', 'redis'], { entryAge: true }),
],
serializer: entryAgeSerializer,
stores: {
targetsById: bentostore()
.useL1Layer(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BentoCache, bentostore } from 'bentocache';
import { memoryDriver } from 'bentocache/drivers/memory';
import { redisDriver } from 'bentocache/drivers/redis';
import { Inject, Injectable, Scope } from 'graphql-modules';
import { cacheMetricsPlugin } from '../../shared/lib/bentocache-cache-metrics';
import { cacheMetricsPlugin, entryAgeSerializer } from '../../shared/lib/bentocache-cache-metrics';
import { REDIS_INSTANCE, type Redis } from '../../shared/providers/redis';
import { TargetStore } from './target-store';

Expand All @@ -22,7 +22,10 @@ export class TargetsBySlugCache {
) {
this.cache = new BentoCache({
default: 'targetsBySlug',
plugins: [cacheMetricsPlugin('bentocache:targetsBySlug')],
plugins: [
cacheMetricsPlugin('bentocache:targetsBySlug', ['memory', 'redis'], { entryAge: true }),
],
serializer: entryAgeSerializer,
stores: {
targetsBySlug: bentostore()
.useL1Layer(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { PostgresDatabasePool } from '@hive/postgres';
import { TaskScheduler } from '@hive/workflows/kit';
import { PurgeTargetTokensTask } from '@hive/workflows/tasks/purge-target-tokens';
import type { Token } from '../../../shared/entities';
import { cacheMetricsPlugin } from '../../shared/lib/bentocache-cache-metrics';
import { cacheMetricsPlugin, entryAgeSerializer } from '../../shared/lib/bentocache-cache-metrics';
import { Logger } from '../../shared/providers/logger';
import { REDIS_INSTANCE, type Redis } from '../../shared/providers/redis';
import { hashTargetToken, TargetTokenStorage } from './target-token-storage';
Expand All @@ -32,7 +32,10 @@ export class TargetTokenCache {
) {
this.cache = new BentoCache({
default: 'targetTokens',
plugins: [cacheMetricsPlugin('bentocache:target-tokens')],
plugins: [
cacheMetricsPlugin('bentocache:target-tokens', ['memory', 'redis'], { entryAge: true }),
],
serializer: entryAgeSerializer,
stores: {
targetTokens: bentostore({ prefix: 'bentocache:target-tokens' })
.useL1Layer(
Expand Down
2 changes: 1 addition & 1 deletion packages/services/schema/src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function createCache(options: {
}

const ttlMs = options.ttlMs;
const cacheMetrics = createCacheMetrics(prefix);
const cacheMetrics = createCacheMetrics(prefix, ['redis']);

async function readAction<T>(id: string): Promise<State<T> | null> {
const action = await redis.get(id);
Expand Down
44 changes: 37 additions & 7 deletions packages/services/service-common/src/cache-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const cacheRequests = new promClient.Counter({
name: 'hive_cache_requests_total',
help: 'Cache lookups per feature. feature is the Redis key prefix the cache writes under.',
// result: hit, graced_hit (stale value served within its grace period) or miss.
// layer: memory or redis for hits; empty for misses.
// layer: memory or redis for hits; empty for graced hits and misses.
labelNames: ['feature', 'result', 'layer'],
});

Expand All @@ -14,11 +14,18 @@ const cacheWrites = new promClient.Counter({
labelNames: ['feature'],
});

const cacheEntryAge = new promClient.Histogram({
name: 'hive_cache_entry_age_seconds',
help: 'Time since a cache entry was written, observed each time it is read. result: hit or graced_hit.',
labelNames: ['feature', 'result'],
buckets: [1, 5, 15, 30, 60, 120, 300, 360, 600, 1_800, 3_600, 10_800, 21_600, 43_200, 86_400],
});

export type CacheLayer = 'memory' | 'redis';

export type CacheMetrics = {
hit(layer: CacheLayer): void;
gracedHit(layer: CacheLayer): void;
hit(layer: CacheLayer, ageSeconds?: number): void;
gracedHit(ageSeconds?: number): void;
miss(): void;
write(): void;
};
Expand All @@ -27,14 +34,37 @@ export type CacheMetrics = {
* Records hits, misses and writes of one cache.
* `feature` should be the Redis key prefix of the cache, so these metrics line up with a scan of
* the keyspace grouped by prefix.
* `layers` are the layers the cache has, and `entryAge` says that it passes an age with its hits.
* Every series the cache can emit is created at zero.
*/
export function createCacheMetrics(feature: string): CacheMetrics {
export function createCacheMetrics(
feature: string,
layers: CacheLayer[],
options: { entryAge?: boolean } = {},
): CacheMetrics {
for (const layer of layers) {
cacheRequests.inc({ feature, result: 'hit', layer }, 0);
}
cacheRequests.inc({ feature, result: 'graced_hit', layer: '' }, 0);
cacheRequests.inc({ feature, result: 'miss', layer: '' }, 0);
cacheWrites.inc({ feature }, 0);
if (options.entryAge) {
cacheEntryAge.zero({ feature, result: 'hit' });
cacheEntryAge.zero({ feature, result: 'graced_hit' });
}

return {
hit(layer) {
hit(layer, ageSeconds) {
cacheRequests.inc({ feature, result: 'hit', layer });
if (ageSeconds !== undefined) {
cacheEntryAge.observe({ feature, result: 'hit' }, ageSeconds);
}
},
gracedHit(layer) {
cacheRequests.inc({ feature, result: 'graced_hit', layer });
gracedHit(ageSeconds) {
cacheRequests.inc({ feature, result: 'graced_hit', layer: '' });
if (ageSeconds !== undefined) {
cacheEntryAge.observe({ feature, result: 'graced_hit' }, ageSeconds);
}
},
miss() {
cacheRequests.inc({ feature, result: 'miss', layer: '' });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type { Context } from '../context';
import { defineTask, implementTask } from '../kit.js';
import { createSchemaObject } from '../lib/schema/provider';

const cacheMetrics = createCacheMetrics('schema-explorer-snapshot');
const cacheMetrics = createCacheMetrics('schema-explorer-snapshot', []);

export const SchemaExplorerSnapshotBuildTask = defineTask({
name: 'schemaExplorerSnapshotBuild',
Expand Down
Loading