Skip to content

Commit

Permalink
cache for saveNestedDataHash calls to prevent duplicate writes
Browse files Browse the repository at this point in the history
Add a cache for saveNestedDataHash calls to prevent duplicate writes.
Add a metrics counter for the number of duplicate saveNestedDataHash calls.

In an environment with ~830 calls to saveNestedDataHash per second after
7 minutes of operation(cache entry TTL), the amount of cached keys was
~349k, with a total of ~33MB of data stored in the cache.

Total amount of duplicated calls was 1428.
  • Loading branch information
karlprieb committed Sep 18, 2024
1 parent d685d92 commit baf1c43
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/database/standalone-sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import * as R from 'ramda';
import sql from 'sql-bricks';
import * as winston from 'winston';
import CircuitBreaker from 'opossum';
import NodeCache from 'node-cache';

// TODO enable eslint
/* eslint-disable */
Expand Down Expand Up @@ -2432,6 +2433,8 @@ export class StandaloneSqliteDatabase
Awaited<ReturnType<StandaloneSqliteDatabase['getTransactionAttributes']>>
>;

private saveNestedDataHashCache: NodeCache;

constructor({
log,
coreDbPath,
Expand Down Expand Up @@ -2505,6 +2508,16 @@ export class StandaloneSqliteDatabase
this.getTransactionAttributesCircuitBreaker,
]);

//
// Initialize save nested data hash cache
//

this.saveNestedDataHashCache = new NodeCache({
stdTTL: 60 * 7, // 7 minutes
checkperiod: 60, // 1 minute
useClones: false,
});

//
// Initialize workers
//
Expand Down Expand Up @@ -2924,6 +2937,19 @@ export class StandaloneSqliteDatabase
parentId: string;
dataOffset: number;
}): Promise<void> {
const key = `${hash}:${parentId}`;

console.log('cache size:', this.saveNestedDataHashCache.getStats());

if (this.saveNestedDataHashCache.get(key)) {
metrics.saveMethodsDuplicateCounter.inc({
method: 'saveNestedDataHash',
});

return;
}
this.saveNestedDataHashCache.set(key, true);

return this.queueWrite('data', 'saveNestedDataHash', [
{
hash,
Expand Down
6 changes: 6 additions & 0 deletions src/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ export const methodDurationSummary = new promClient.Summary({
labelNames: ['worker', 'role', 'method'],
});

export const saveMethodsDuplicateCounter = new promClient.Counter({
name: 'save_methods_duplicate_total',
help: 'Count of duplicate calls to save methods',
labelNames: ['method'],
});

//
// Block importer metrics
//
Expand Down

0 comments on commit baf1c43

Please sign in to comment.