Skip to content

Commit e1a3452

Browse files
authored
docs(batch): add section on how to trace batch processing (#1673)
* docs(batch): tracing batch processing * docs(batch): add guidance on how to trace batch processing
1 parent 6d2de72 commit e1a3452

File tree

7 files changed

+113
-36
lines changed

7 files changed

+113
-36
lines changed

Diff for: docs/index.md

+16-15
Original file line numberDiff line numberDiff line change
@@ -294,20 +294,21 @@ Core utilities such as Tracing, Logging, and Metrics will be available across al
294294
???+ info
295295
Explicit parameters take precedence over environment variables
296296

297-
| Environment variable | Description | Utility | Default |
298-
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ------------------- |
299-
| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | All | `service_undefined` |
300-
| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | [Metrics](./core/metrics) | `default_namespace` |
301-
| **POWERTOOLS_TRACE_ENABLED** | Explicitly disables tracing | [Tracer](./core/tracer) | `true` |
302-
| **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Captures Lambda or method return as metadata. | [Tracer](./core/tracer) | `true` |
303-
| **POWERTOOLS_TRACER_CAPTURE_ERROR** | Captures Lambda or method exception as metadata. | [Tracer](./core/tracer) | `true` |
304-
| **POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS** | Captures HTTP(s) requests as segments. | [Tracer](./core/tracer) | `true` |
305-
| **POWERTOOLS_LOGGER_LOG_EVENT** | Logs incoming event | [Logger](./core/logger) | `false` |
306-
| **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logger](./core/logger) | `0` |
307-
| **POWERTOOLS_DEV** | Increase JSON indentation to ease debugging when running functions locally or in a non-production environment | [Logger](./core/logger) | `false` |
308-
| **LOG_LEVEL** | Sets logging level | [Logger](./core/logger) | `INFO` |
309-
| **POWERTOOLS_PARAMETERS_MAX_AGE** | Adjust how long values are kept in cache (in seconds) | [Parameters](./utilities/parameters) | `5` |
310-
| **POWERTOOLS_PARAMETERS_SSM_DECRYPT** | Sets whether to decrypt or not values retrieved from AWS Systems Manager Parameters Store | [Parameters](./utilities/parameters) | `false` |
297+
| Environment variable | Description | Utility | Default |
298+
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------- |
299+
| **POWERTOOLS_SERVICE_NAME** | Set service name used for tracing namespace, metrics dimension and structured logging | All | `service_undefined` |
300+
| **POWERTOOLS_METRICS_NAMESPACE** | Set namespace used for metrics | [Metrics](core/metrics.md) | `default_namespace` |
301+
| **POWERTOOLS_TRACE_ENABLED** | Explicitly disables tracing | [Tracer](core/tracer.md) | `true` |
302+
| **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Capture Lambda or method return as metadata. | [Tracer](core/tracer.md) | `true` |
303+
| **POWERTOOLS_TRACER_CAPTURE_ERROR** | Capture Lambda or method exception as metadata. | [Tracer](core/tracer.md) | `true` |
304+
| **POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS** | Capture HTTP(s) requests as segments. | [Tracer](core/tracer.md) | `true` |
305+
| **POWERTOOLS_LOGGER_LOG_EVENT** | Log incoming event | [Logger](core/logger.md) | `false` |
306+
| **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logger](core/logger.md) | `0` |
307+
| **POWERTOOLS_DEV** | Increase JSON indentation to ease debugging when running functions locally or in a non-production environment | [Logger](core/logger.md) | `false` |
308+
| **LOG_LEVEL** | Set logging level | [Logger](core/logger.md) | `INFO` |
309+
| **POWERTOOLS_PARAMETERS_MAX_AGE** | Adjust how long values are kept in cache (in seconds) | [Parameters](utilities/parameters.md) | `5` |
310+
| **POWERTOOLS_PARAMETERS_SSM_DECRYPT** | Set whether to decrypt or not values retrieved from AWS Systems Manager Parameters Store | [Parameters](utilities/parameters.md) | `false` |
311+
| **POWERTOOLS_IDEMPOTENCY_DISABLED** | Disable the Idempotency logic without changing your code, useful for testing | [Idempotency](utilities/idempotency.md) | `false` |
311312

312313
Each Utility page provides information on example values and allowed values.
313314

@@ -331,7 +332,7 @@ The following companies, among others, use Powertools:
331332

332333
### Sharing your work
333334

334-
Share what you did with Powertools for AWS Lambda (TypeScript) 💞💞. Blog post, workshops, presentation, sample apps and others. Check out what the community has already shared about Powertools for AWS Lambda (TypeScript) [here](./we_made_this).
335+
Share what you did with Powertools for AWS Lambda (TypeScript) 💞💞. Blog post, workshops, presentation, sample apps and others. Check out what the community has already shared about Powertools for AWS Lambda (TypeScript) [here](we_made_this.md).
335336

336337
### Using Lambda Layer
337338

Diff for: docs/snippets/batch/advancedTracingRecordHandler.ts

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import {
2+
BatchProcessor,
3+
EventType,
4+
processPartialResponse,
5+
} from '@aws-lambda-powertools/batch';
6+
import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer';
7+
import middy from '@middy/core';
8+
import type {
9+
SQSEvent,
10+
SQSRecord,
11+
Context,
12+
SQSBatchResponse,
13+
} from 'aws-lambda';
14+
15+
const processor = new BatchProcessor(EventType.SQS);
16+
const tracer = new Tracer({ serviceName: 'serverlessAirline' });
17+
18+
const recordHandler = (record: SQSRecord): void => {
19+
const subsegment = tracer.getSegment()?.addNewSubsegment('### recordHandler'); // (1)!
20+
subsegment?.addAnnotation('messageId', record.messageId); // (2)!
21+
22+
const payload = record.body;
23+
if (payload) {
24+
try {
25+
const item = JSON.parse(payload);
26+
// do something with the item
27+
subsegment?.addMetadata('item', item);
28+
} catch (error) {
29+
subsegment?.addError(error);
30+
throw error;
31+
}
32+
}
33+
34+
subsegment?.close(); // (3)!
35+
};
36+
37+
export const handler = middy(
38+
async (event: SQSEvent, context: Context): Promise<SQSBatchResponse> => {
39+
return processPartialResponse(event, recordHandler, processor, {
40+
context,
41+
});
42+
}
43+
).use(captureLambdaHandler(tracer));

Diff for: docs/snippets/batch/customPartialProcessor.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import {
55
} from '@aws-sdk/client-dynamodb';
66
import { marshall } from '@aws-sdk/util-dynamodb';
77
import {
8-
BasePartialProcessor,
8+
EventType,
9+
BasePartialBatchProcessor,
910
processPartialResponse,
1011
} from '@aws-lambda-powertools/batch';
1112
import type {
@@ -17,12 +18,12 @@ import type { SQSEvent, Context, SQSBatchResponse } from 'aws-lambda';
1718

1819
const tableName = process.env.TABLE_NAME || 'table-not-found';
1920

20-
class MyPartialProcessor extends BasePartialProcessor {
21+
class MyPartialProcessor extends BasePartialBatchProcessor {
2122
#tableName: string;
2223
#client?: DynamoDBClient;
2324

2425
public constructor(tableName: string) {
25-
super();
26+
super(EventType.SQS);
2627
this.#tableName = tableName;
2728
}
2829

Diff for: docs/stylesheets/extra.css

+31-10
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,53 @@
1-
@font-face {
2-
font-size: 0.65rem;
1+
.md-grid {
2+
max-width: 90vw
33
}
44

5-
.md-grid {
6-
max-width: 81vw;
5+
.highlight .hll {
6+
background-color: lavender;
7+
8+
[data-md-color-scheme="slate"] {
9+
background-color: rgb(69, 48, 164)
10+
}
11+
}
12+
13+
.md-typeset table:not([class]) {
14+
font-size: 0.75rem
715
}
816

917
.md-typeset a {
10-
border-bottom: 0.1px dashed black;
18+
border-bottom: 0.1px dashed black
19+
}
20+
21+
.md-typeset table:not([class]) {
22+
font-size: 0.75rem
23+
}
24+
25+
.md-tabs__link {
26+
font-size: 0.8rem
27+
}
28+
29+
.md-tabs__link--active {
30+
border-bottom: 6px solid white
1131
}
1232

1333
.md-nav__link--active {
14-
font-weight: bold;
34+
font-weight: bold
1535
}
1636

1737
.md-typeset .admonition, .md-typeset details {
18-
font-size: 0.70rem;
38+
font-size: 0.70rem
1939
}
2040

2141
[data-md-color-scheme="slate"] {
22-
--md-typeset-a-color: rgb(28, 152, 152);
42+
--md-typeset-a-color: rgb(28, 152, 152)
2343
}
2444

2545
.copyMe {
2646
cursor: pointer;
2747
border-bottom: 0.1px dashed black;
2848
}
2949

30-
p code {
31-
font-weight: bolder;
50+
p > code,
51+
li > code {
52+
font-weight: bold
3253
}

Diff for: docs/utilities/batch.md

+14-2
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ For these scenarios, you can subclass `BatchProcessor` and quickly override `suc
409409
???+ example
410410
Let's suppose you'd like to add a metric named `BatchRecordFailures` for each batch record that failed processing
411411

412-
```typescript hl_lines="5-6 17 21 25 31 35 50-52" title="Extending failure handling mechanism in BatchProcessor"
412+
```typescript hl_lines="17 21 25 31 35" title="Extending failure handling mechanism in BatchProcessor"
413413
--8<-- "docs/snippets/batch/extendingFailure.ts"
414414
```
415415

@@ -448,10 +448,22 @@ classDiagram
448448

449449
You can then use this class as a context manager, or pass it to `processPartialResponse` to process the records in your Lambda handler function.
450450

451-
```typescript hl_lines="8 12-14 20 29 40 61 72 83 93-95" title="Creating a custom batch processor"
451+
```typescript hl_lines="21 30 41 62 73 84" title="Creating a custom batch processor"
452452
--8<-- "docs/snippets/batch/customPartialProcessor.ts"
453453
```
454454

455+
## Tracing with AWS X-Ray
456+
457+
You can use Tracer to create subsegments for each batch record processed. To do so, you can open a new subsegment for each record, and close it when you're done processing it. When adding annotations and metadata to the subsegment, you can do so directly without calling `tracer.setSegment(subsegment)`. This allows you to work with the subsegment directly and avoid having to either pass the parent subsegment around or have to restore the parent subsegment at the end of the record processing.
458+
459+
```ts
460+
--8<-- "docs/snippets/batch/advancedTracingRecordHandler.ts"
461+
```
462+
463+
1. Retrieve the current segment, then create a subsegment for the record being processed
464+
2. You can add annotations and metadata to the subsegment directly without calling `tracer.setSegment(subsegment)`
465+
3. Close the subsegment when you're done processing the record
466+
455467
## Testing your code
456468

457469
As there is no external calls, you can unit test your code with `BatchProcessor` quite easily.

Diff for: docs/utilities/parameters.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ You can use the `awsSdkV3Client` parameter via any of the available [Provider Cl
392392
| [DynamoDBProvider](#dynamodbprovider) | `new DynamoDBClient();` |
393393

394394
???+ question "When is this useful?"
395-
Injecting a custom AWS SDK v3 client allows you to [apply tracing](/core/tracer/#patching-aws-sdk-clients) or make unit/snapshot testing easier, including SDK customizations.
395+
Injecting a custom AWS SDK v3 client allows you to [apply tracing](../core/tracer.md#patching-aws-sdk-clients) or make unit/snapshot testing easier, including SDK customizations.
396396

397397
=== "SSMProvider"
398398
```typescript hl_lines="5 7"

Diff for: mkdocs.yml

+4-5
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,10 @@ nav:
1010
- Roadmap: roadmap.md
1111
- API reference: api/" target="_blank
1212
- We Made This (Community): we_made_this.md
13-
- Core utilities:
13+
- Features:
1414
- core/tracer.md
1515
- core/logger.md
1616
- core/metrics.md
17-
- Utilities:
1817
- utilities/parameters.md
1918
- utilities/idempotency.md
2019
- utilities/batch.md
@@ -39,15 +38,12 @@ theme:
3938
features:
4039
- header.autohide
4140
- navigation.sections
42-
- navigation.expand
4341
- navigation.top
4442
- navigation.instant
4543
- navigation.indexes
4644
- navigation.tracking
4745
- content.code.annotate
4846
- content.code.copy
49-
- toc.follow
50-
- toc.integrate
5147
- announce.dismiss
5248
icon:
5349
repo: fontawesome/brands/github
@@ -65,6 +61,7 @@ markdown_extensions:
6561
- pymdownx.snippets:
6662
base_path: "."
6763
check_paths: true
64+
restrict_base_path: false
6865
- meta
6966
- toc:
7067
permalink: true
@@ -79,6 +76,8 @@ markdown_extensions:
7976
- name: mermaid
8077
class: mermaid
8178
format: !!python/name:pymdownx.superfences.fence_code_format
79+
- pymdownx.tasklist:
80+
custom_checkbox: true
8281

8382
copyright: Copyright &copy; 2023 Amazon Web Services
8483

0 commit comments

Comments
 (0)