-
Notifications
You must be signed in to change notification settings - Fork 145
feat(core): add operation-level sample rates to the usage plugin #8181
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ChaoyangS
wants to merge
2
commits into
graphql-hive:main
Choose a base branch
from
ChaoyangS:feat/operation-level-sample-rates
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+454
−4
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| --- | ||
| '@graphql-hive/core': minor | ||
| --- | ||
|
|
||
| Add operation-level sample rates to the usage plugin via the new `sampleRates` option. | ||
|
|
||
| Each rule matches operations by exact `name` or by `regex` (tested against the operation name) and applies its own `sampleRate`. The first matching rule wins; operations that don't match any rule fall back to the global `sampleRate` (default `1.0`). This lets you sample known high-volume operations aggressively while keeping 100% visibility into low-volume operations, instead of choosing a single global rate that either overpays on quota or misses rare operations. | ||
|
|
||
| `exclude` still takes precedence (excluded operations are never reported), and `sampler`, when provided, continues to override both `sampleRate` and `sampleRates`. | ||
|
|
||
| ```ts | ||
| usage: { | ||
| sampleRate: 1.0, // fallback for unmatched operations | ||
| sampleRates: [ | ||
| { name: 'SampledQuery', sampleRate: 0.1 }, | ||
| { regex: /^HighVolume/, sampleRate: 0.1 }, | ||
| ], | ||
| } | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| /** | ||
| * Demo / reproduction for operation-level sample rates. | ||
| * | ||
| * Scenario from the feature request: a system mixes a few very high-volume | ||
| * operations with many low-volume ones. Global sampling forces a bad trade-off: | ||
| * - sample everything at 100% -> the high-volume ops blow the usage quota | ||
| * - sample everything at e.g. 5% -> the low-volume ops are missed entirely | ||
| * | ||
| * Operation-level sample rates let us sample the known high-volume operations | ||
| * aggressively while keeping 100% visibility into low-volume operations. | ||
| * | ||
| * Run from the repo root: | ||
| * pnpm --filter @graphql-hive/core exec tsx demo/operation-sample-rates.ts | ||
| * or from packages/libraries/core: | ||
| * pnpm exec tsx demo/operation-sample-rates.ts | ||
| */ | ||
| import { parse } from 'graphql'; | ||
| import { operationSampling, randomSampling } from '../src/client/sampling.js'; | ||
| import type { SamplingContext } from '../src/client/types.js'; | ||
|
|
||
| const document = parse(/* GraphQL */ ` | ||
| query { | ||
| __typename | ||
| } | ||
| `); | ||
|
|
||
| function ctx(operationName: string): SamplingContext { | ||
| return { operationName, document, variableValues: null, contextValue: undefined }; | ||
| } | ||
|
|
||
| // A simulated traffic mix: operation name -> number of executions in the window. | ||
| const traffic: Array<{ operationName: string; volume: number }> = [ | ||
| { operationName: 'HighVolumeFeed', volume: 500_000 }, | ||
| { operationName: 'HighVolumePing', volume: 250_000 }, | ||
| { operationName: 'CheckoutMutation', volume: 1_200 }, | ||
| { operationName: 'AdminAuditReport', volume: 40 }, | ||
| { operationName: 'RareMigrationQuery', volume: 8 }, | ||
| ]; | ||
|
|
||
| const totalOps = traffic.reduce((sum, t) => sum + t.volume, 0); | ||
|
|
||
| function simulate(shouldInclude: (c: SamplingContext) => boolean) { | ||
| const sent = new Map<string, number>(); | ||
| for (const { operationName, volume } of traffic) { | ||
| let count = 0; | ||
| for (let i = 0; i < volume; i++) { | ||
| if (shouldInclude(ctx(operationName))) count++; | ||
| } | ||
| sent.set(operationName, count); | ||
| } | ||
| return sent; | ||
| } | ||
|
|
||
| function pct(part: number, whole: number) { | ||
| return whole === 0 ? '0%' : `${((part / whole) * 100).toFixed(1)}%`; | ||
| } | ||
|
|
||
| function printResult(title: string, sent: Map<string, number>) { | ||
| console.log(`\n=== ${title} ===`); | ||
| let totalSent = 0; | ||
| for (const { operationName, volume } of traffic) { | ||
| const s = sent.get(operationName) ?? 0; | ||
| totalSent += s; | ||
| const visibility = s > 0 ? 'visible' : 'MISSED'; | ||
| console.log( | ||
| ` ${operationName.padEnd(20)} volume=${String(volume).padStart(7)} ` + | ||
| `sent=${String(s).padStart(7)} (${pct(s, volume).padStart(6)}) ${visibility}`, | ||
| ); | ||
| } | ||
| console.log( | ||
| ` ${'TOTAL'.padEnd(20)} volume=${String(totalOps).padStart(7)} ` + | ||
| `sent=${String(totalSent).padStart(7)} (${pct(totalSent, totalOps)} of quota)`, | ||
| ); | ||
| return totalSent; | ||
| } | ||
|
|
||
| // --- Strategy A: global 100% sampling (full visibility, full quota cost) ----- | ||
| const globalFull = printResult('Global sampleRate = 1.0 (overpay)', simulate(randomSampling(1.0))); | ||
|
|
||
| // --- Strategy B: global 5% sampling (cheap, but loses low-volume ops) -------- | ||
| const globalLow = printResult( | ||
| 'Global sampleRate = 0.05 (low-volume ops missed)', | ||
| simulate(randomSampling(0.05)), | ||
| ); | ||
|
|
||
| // --- Strategy C: operation-level sample rates (the new feature) -------------- | ||
| // Sample the high-volume ops at 1%, keep everything else at 100% via fallback. | ||
| const perOp = printResult( | ||
| 'Operation-level: /^HighVolume/ -> 1%, fallback 100%', | ||
| simulate( | ||
| operationSampling({ | ||
| rates: [{ regex: /^HighVolume/, sampleRate: 0.01 }], | ||
| fallbackSampleRate: 1.0, | ||
| }), | ||
| ), | ||
| ); | ||
|
|
||
| console.log('\n=== Summary ==='); | ||
| console.log(` Global 100%: ${globalFull} ops billed (${pct(globalFull, totalOps)})`); | ||
| console.log(` Global 5%: ${globalLow} ops billed (${pct(globalLow, totalOps)})`); | ||
| console.log(` Operation-level: ${perOp} ops billed (${pct(perOp, totalOps)})`); | ||
| console.log( | ||
| '\n -> Operation-level sampling slashes billed volume like the cheap global rate,', | ||
| ); | ||
| console.log(' while still reporting 100% of the low-volume operations.'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid using the non-null assertion operator (
!) outside of test files, as it can lead to subtle bugs. We can destructure the properties fromrateand let TypeScript's control flow analysis narrow the type ofregexautomatically when checkingregex instanceof RegExp.References
!) outside of test files, as it can lead to subtle bugs.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
addressed.