Skip to content

Commit 0428512

Browse files
committed
feat: Improve sampling algorithm
1 parent e26be68 commit 0428512

File tree

1 file changed

+22
-2
lines changed
  • node/packages/aws-lambda-sdk/instrument

1 file changed

+22
-2
lines changed

node/packages/aws-lambda-sdk/instrument/index.js

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const sendTelemetry = require('./lib/send-telemetry');
1111
const flushSpans = require('./lib/auto-send-spans').flush;
1212
const filterCapturedEvent = require('./lib/filter-captured-event');
1313
const invocationContextAccessor = require('./lib/invocation-context-accessor');
14+
const isApiEvent = require('./lib/is-api-event');
1415
const pkgJson = require('../package');
1516

1617
const serverlessSdk = require('./lib/sdk');
@@ -98,15 +99,34 @@ const reportResponse = async (response, context, endTime) => {
9899
await sendTelemetry('request-response', payloadBuffer);
99100
};
100101

102+
let requestCounter = 0;
103+
let lastCounterResetTime = 0;
104+
101105
const reportTrace = ({ isErrorOutcome }) => {
102-
// Sample out 80% of traces in production mode if no warning or error event was reported
103106
const isSampledOut =
104107
(() => {
108+
// This function determines if a trace should be sampled or not
109+
//
110+
// Do not sample when invocation ends with error
105111
if (isErrorOutcome) return false;
112+
// Do not sample when in debug mode
106113
if (serverlessSdk._isDebugMode) return false;
114+
// Do not sample when in dev mode
107115
if (serverlessSdk._isDevMode) return false;
116+
// Do not sample when any error or warning event is captured
108117
if (capturedEvents.some(({ name }) => alertEventNames.has(name))) return false;
109-
return Math.random() > 0.2;
118+
const currentTime = Date.now();
119+
if (currentTime - lastCounterResetTime > 1000) {
120+
lastCounterResetTime = currentTime;
121+
requestCounter = 0;
122+
}
123+
++requestCounter;
124+
// In case of API backed function sample out 3rd and following invocations,
125+
// that happen in a frame of a second
126+
if (isApiEvent()) return requestCounter > 2;
127+
// In other cases do not sample 1st invocation, and sample out 90% of following invocations
128+
if (requestCounter === 1) return false;
129+
return Math.random() > 0.1;
110130
})() || undefined;
111131
const payload = (serverlessSdk._lastTrace = {
112132
isSampledOut,

0 commit comments

Comments
 (0)