@@ -11,6 +11,7 @@ const sendTelemetry = require('./lib/send-telemetry');
11
11
const flushSpans = require ( './lib/auto-send-spans' ) . flush ;
12
12
const filterCapturedEvent = require ( './lib/filter-captured-event' ) ;
13
13
const invocationContextAccessor = require ( './lib/invocation-context-accessor' ) ;
14
+ const isApiEvent = require ( './lib/is-api-event' ) ;
14
15
const pkgJson = require ( '../package' ) ;
15
16
16
17
const serverlessSdk = require ( './lib/sdk' ) ;
@@ -98,15 +99,34 @@ const reportResponse = async (response, context, endTime) => {
98
99
await sendTelemetry ( 'request-response' , payloadBuffer ) ;
99
100
} ;
100
101
102
+ let requestCounter = 0 ;
103
+ let lastCounterResetTime = 0 ;
104
+
101
105
const reportTrace = ( { isErrorOutcome } ) => {
102
- // Sample out 80% of traces in production mode if no warning or error event was reported
103
106
const isSampledOut =
104
107
( ( ) => {
108
+ // This function determines if a trace should be sampled or not
109
+ //
110
+ // Do not sample when invocation ends with error
105
111
if ( isErrorOutcome ) return false ;
112
+ // Do not sample when in debug mode
106
113
if ( serverlessSdk . _isDebugMode ) return false ;
114
+ // Do not sample when in dev mode
107
115
if ( serverlessSdk . _isDevMode ) return false ;
116
+ // Do not sample when any error or warning event is captured
108
117
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 ;
110
130
} ) ( ) || undefined ;
111
131
const payload = ( serverlessSdk . _lastTrace = {
112
132
isSampledOut,
0 commit comments