Skip to content

jaingxyz/aws-data-skills / skills/streaming-into-data-lake

streaming-into-data-lake

Verified

Stream rows continuously into Apache Iceberg tables on S3 Tables (or standard Iceberg on a general purpose bucket) using Amazon Data Firehose with IcebergDestinationConfiguration. Covers the Firehose stream, the optional record-shaping Lambda (ProcessingConfiguration), the Lake Formation grants required for Firehose to write through Glue, and the three-phase CloudFormation deploy that gates the stream on grants existing. Triggers on: stream into data lake, Firehose to S3 Tables, Firehose to Iceberg, real-time ingestion to Iceberg, Firehose IcebergDestinationConfiguration, stream Kinesis to Iceberg, near real-time CDC to data lake, continuous append to Iceberg. Do NOT use for: batch file imports (use ingesting-into-data-lake), creating the destination Iceberg table itself (use creating-data-lake-table), the one-time Lake Formation onboarding (use setting-up-lake-formation), finding tables by fuzzy name (use finding-data-lake-assets), running queries (use querying-data-lake), Glue connections (Firehose does not use them; do not invoke connecting-to-data-source), Kinesis to Lambda to Redshift Data API direct writes (not Iceberg; recommend a different workflow), or producer-side Kafka or MSK setup.

references/transform-lambda.md

View on GitHub
# Firehose Transform Lambda

The Firehose transform Lambda has one job: take each input record and emit exactly one output record whose top-level JSON keys exactly match the destination Iceberg column names, with two extra metadata keys Firehose requires.

## The column-mapping footgun

Firehose writes records to Iceberg by parsing each record as JSON and matching top-level keys to Iceberg column names. The match is case-sensitive and exact. There is no implicit normalization.

Failure modes seen in production:

| Lambda emits | Iceberg schema has | Result |
|---|---|---|
| `record_id` | `recordid` | Every record discarded; error bucket logs `Iceberg.MissingColumnWithinRecord` |
| `customerId` | `customer_id` | Same |
| `Amount` | `amount` | Same |
| `event_ts` (ISO-8601 string) | `event_ts` (`timestamp`) | Records silently land with timestamps in year 1970 or year 50000+ |

Mitigation: write a unit test that diffs the Lambda's output keys against the Glue table schema before deploying. The deploy script SHOULD fail closed when the diff is non-empty.

## Microsecond timestamps

Iceberg `timestamp` and `timestamp_ntz` columns expect microseconds since epoch as int64. Common bugs:

```python
# CORRECT, primary case: source carries a millisecond timestamp (e.g.
# DSQL CDC `ts_ms`). Multiply by 1000 for microseconds. This preserves
# the source-side commit ordering, which is what downstream
# ROW_NUMBER reconstruction relies on.
output["event_ts"] = int(payload["ts_ms"]) * 1000

# CORRECT, when source provides a datetime object
output["event_ts"] = int(dt.timestamp() * 1_000_000)

# WRONG: wall-clock at the Lambda. Loses source commit ordering;
# multiple events in the same Firehose buffer share one timestamp.
output["event_ts"] = int(time.time() * 1_000_000)

# WRONG: milliseconds when the column type is timestamp, lands rows with
# timestamps ~1000x too small
output["event_ts"] = int(time.time() * 1000)

# WRONG: ISO string, Firehose discards as Iceberg.SchemaTypeMismatch because the type does not match
output["event_ts"] = datetime.utcnow().isoformat()
```

For `date` columns, emit days since epoch as int32. For `string` timestamps where Iceberg type is `string`, ISO-8601 is fine.

## Required output metadata

Per the Firehose data transformation contract, every output record MUST include:

- `recordId` (string) - echoed unchanged from the input record. Firehose uses this to acknowledge per-record success.
- `result` (string) - one of `Ok`, `Dropped`, `ProcessingFailed`. Anything else fails the entire batch.
- `data` (string, base64-encoded) - the JSON payload Firehose will parse for column matching. Required for `Ok`. Optional for `Dropped` / `ProcessingFailed`.

Additionally, ONLY when the stream is in MERGE mode (`AppendOnly: false`) or has multiple tables in `DestinationTableConfigurationList`, the record must also include:

- `metadata.otfMetadata.destinationDatabaseName` and `metadata.otfMetadata.destinationTableName` - per-record routing for fan-out.
- `metadata.otfMetadata.operation` - one of `insert`, `update`, `delete`.

For the typical CDC-archive case (`AppendOnly: true`, single static destination table), DO NOT include `metadata.otfMetadata`. Firehose interprets a present-but-stale `metadata` block as a routing decision and may reject the record. The companion repo's transform Lambda emits only `{recordId, result, data}` for this reason.

## Generalized template

```python
import base64
import json
import time
from typing import Any

def transform(payload: dict[str, Any]) -> dict[str, Any]:
    """Map a source record to the Iceberg column shape.
    Override this per pipeline. Return None to drop the record."""
    # Example: rename keys, convert timestamps to microseconds, attach a primary key.
    out = {
        "record_id": str(payload["id"]),
        "customer_id": payload["customerId"],
        "amount": float(payload["amount"]),
        "event_ts": int(payload["epochSeconds"] * 1_000_000),
    }
    return out

def lambda_handler(event, _context):
    output_records = []
    for record in event["records"]:
        record_id = record["recordId"]
        try:
            raw = base64.b64decode(record["data"]).decode("utf-8")
            payload = json.loads(raw)
            transformed = transform(payload)
            if transformed is None:
                output_records.append({
                    "recordId": record_id,
                    "result": "Dropped",
                    "data": record["data"],
                })
                continue
            encoded = base64.b64encode(
                json.dumps(transformed).encode("utf-8")
            ).decode("utf-8")
            # AppendOnly: true (the recommended default for CDC archives).
            # Single static destination table, no per-record routing.
            output_records.append({
                "recordId": record_id,
                "result": "Ok",
                "data": encoded,
            })
            # MERGE mode (AppendOnly: false) or fan-out: uncomment and set
            # the destination + operation. Firehose rejects stale metadata
            # blocks under AppendOnly, so leave commented in single-table mode.
            # output_records[-1]["metadata"] = {
            #     "otfMetadata": {
            #         "destinationDatabaseName": "<db>",
            #         "destinationTableName": "<table>",
            #         "operation": "insert",  # or "update" / "delete"
            #     }
            # }
        except Exception:  # noqa: BLE001
            output_records.append({
                "recordId": record_id,
                "result": "ProcessingFailed",
                "data": record["data"],
            })
    return {"records": output_records}
```

The default shape above is `AppendOnly: true`: one output record per input, no `metadata` block. For MERGE mode, uncomment the routing block and set the destination and operation per record.

## Lambda role permissions

The Lambda's execution role needs:

- Standard `AWSLambdaBasicExecutionRole` for CloudWatch Logs.
- No Iceberg or S3 permissions; the Lambda never writes to Iceberg directly. Firehose does that with the Firehose role.

## Buffer and timeout

- Lambda timeout: 60 seconds. Firehose times out the invoke at 60 s and treats the batch as failed.
- Memory: 256 MB is enough for JSON-only transforms. Bump to 1024 MB if the transform decompresses or parses large payloads.
- Reserved concurrency: leave unset. Firehose throttles itself.
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 322kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 118kUpdated Claude CodeCodexVerifiedInstall