Reusable with context

Engineering Snippets.

Not a code dump. Every snippet has a purpose, evidence level, operational notes and — for deeper entries — why it works, when to use it and what can go wrong.

SQLPRODUCTION

Deterministic Deduplication — Latest Record

Keep the most recent row for each logical identity using ROW_NUMBER().

sqldeduprow_numberdata-extension
SQLPRODUCTION

Anti-Join / Exclusion Audience

Find records in a source population that do not have a qualifying event or membership.

sqlleft joinexclusionaudience
SQLPRODUCTION

Latest Version per Journey

Return only the highest version number for each JourneyID and optionally exclude inactive states.

sqljourneyversionjourney builder
SQLPRODUCTION

Journey → Activity → Email Tracking

Map email tracking events back to Journey Builder journey and activity names.

sqljourneytrackingsent
SQLPRODUCTION

Find Job IDs for Journey Email Activities

Resolve Journey Builder email activities to their JobID values for reporting and troubleshooting.

sqljobidjourneyemail
SQLPRODUCTION

Subscriber Engagement — 120 Day Flags

Create recent-open/recent-click flags and last engagement dates for an audience.

sqlengagementopenclick
SQLPRODUCTION

Recent Bounce Diagnostics

Extract recent bounce category and SMTP details for deliverability investigation.

sqlbouncesmtpdeliverability
SQLPRODUCTION

Current Email Subscriber Status

Read current All Subscribers status, bounce count and unsubscribe date from _Subscribers.

sqlsubscribersstatusall subscribers
SQLPRODUCTION

Random Audience Split with NTILE()

Randomly divide an eligible audience into similarly sized groups.

sqlntilenewidab test
SQLPRODUCTION

Incremental Window with Overlap

Reprocess a small overlap window so late-arriving records are not silently lost.

sqlincrementaletlwatermark
AMPscriptPRODUCTION

Defensive LookupRows()

Handle zero-row lookups explicitly before reading row fields.

ampscriptlookuprowsrowcountdefensive
AMPscriptPRODUCTION

Tracked Dynamic URL

Build a dynamic URL and preserve Marketing Cloud click tracking with RedirectTo().

ampscriptredirecttoutmtracking
AMPscriptPROJECT

Iterate JSON Arrays with BuildRowsetFromJson()

Convert a JSON array into a rowset and iterate it in AMPscript.

ampscriptjsonbuildrowsetfromjsonapi event
AMPscriptPROJECT

Encrypted CloudPagesURL Parameters

Pass subscriber/context values to a CloudPage without exposing raw query parameters.

ampscriptcloudpagescloudpagesurlsecurity
CloudPagesPRODUCTION

CloudPage — Read & Validate Request Parameters

Read request parameters and reject missing required identity context.

cloudpagesampscriptrequestparametervalidation
SSJSPROJECT

SSJS HTTP POST Webhook

Send a JSON payload to an external webhook from a Script Activity.

ssjshttpwebhookintegration
SSJS / WSProxyPROJECT

WSProxy Retrieve with Pagination

Retrieve SOAP objects beyond a single response page using RequestID / getNextBatch().

ssjswsproxypaginationsoap
SSJS / WSProxyPROJECT

WSProxy DataExtensionObject UpdateAdd Batch

Batch upsert Data Extension rows through the SOAP object model.

ssjswsproxyupdatebatchdata extension
Email OpsPRODUCTION

Email HTML — Minimal Defensive Shell

Baseline email markup with viewport, dark-mode metadata and Outlook DPI handling.

emailhtmloutlookdark mode
n8nLAB

n8n Public Webhook Contract

Small public webhook contract for portfolio/contact workflows with explicit validation boundaries.

n8nwebhookapivalidation
DockerLAB

Docker Compose — Service Baseline

A small baseline for restart policy, health checks and environment-file separation.

dockercomposehealthchecklinux
SecretsSTUDY

Never Hardcode Secrets in SFMC Scripts

Audit Script Activities and Content Builder assets for embedded credentials and tokens.

securityssjssecretsaudit
PythonPROJECT

Python — Normalize Extracted Metadata

Normalize inconsistent metadata keys into a stable schema before reporting/export.

pythonmetadatanormalizationsfmc-auditor
LLM EngineeringSTUDY

LLM Assistance — Constrain Output to a Schema

Use explicit schemas and validation when AI assists with repeatable engineering work.

aillmschemavalidation
SQLPRODUCTION

ROW_NUMBER() with a Deterministic Tie-Breaker

Make deduplication deterministic when the main timestamp can tie.

sqlrow_numberdeduptie breaker
SQLPRODUCTION

ROW_NUMBER() with Business Priority

Choose a surviving customer row by source trust first, recency second.

sqlrow_numbercasegolden record
SQLPRODUCTION

Second Most Recent Record per Key

Use ROW_NUMBER() as a history/debugging tool, not only for rn = 1.

sqlrow_numberhistorydebugging
SQLPRODUCTION

SARGable Rolling Date Window

Filter recent Data View rows without wrapping the source date column in a function.

sqlperformancedateaddsargable
SQLPRODUCTION

Pre-Aggregate Tracking Before Joining

Reduce event grain before combining behavior tables.

sqltrackingaggregationperformance
SQLPRODUCTION

First Unique Open in a Window

Return the first unique open date per subscriber within a defined analysis window.

sqlopenisuniquemin
SQLPRODUCTION

Latest Unique Click per Subscriber

Collapse click tracking to one latest engagement timestamp per subscriber.

sqlclickmaxengagement
SQLPRODUCTION

COALESCE() for Ordered Fallback Values

Choose the first non-null value from multiple candidate fields.

sqlcoalescenullfallback
SQLPRODUCTION

CASE-Based Business Segmentation

Translate explicit business rules into a readable segment label.

sqlcasesegmentationbusiness rules
SQLPRODUCTION

UNION ALL for Multi-Source Staging

Normalize multiple source populations into one staging shape without deduplicating too early.

sqlunion allmultibrandstaging
SQLPROJECT

Fast Approximate Split with _CustomObjectKey Modulo

Use the hidden row key for cheap approximate segmentation of a standard Data Extension.

sqlcustomobjectkeymodulosegmentation
SQLPRODUCTION

TOP + ORDER BY for a Limited Ordered Set

Select a limited number of rows using SQL Server-style TOP syntax.

sqltoporder byt-sql
SQLPRODUCTION

Explicit Column Contract — No SELECT *

Promote production queries with explicit output columns instead of SELECT *.

sqlselect starschemamigration
SQLPRODUCTION

Stage Before Large Add/Update

Move expensive transformation into an overwrite staging DE before a large Add/Update write.

sqladd updatestagingperformance
Automation HealthPRODUCTION

Latest Run Status per Automation

Return the latest known Automation Studio run for each AutomationCustomerKey.

sqlautomation studioautomationinstancerow_number
Automation HealthPRODUCTION

Automation Failures / Skips in the Last 24h

Surface recent unhealthy Automation Studio runs with the first error detail.

sqlautomation studioerrorskipped
Automation HealthPRODUCTION

Automation Activity Runtime & Error Health

Measure average activity runtime and failure count by activity key.

sqlautomationactivityinstanceruntimeerrors
Automation HealthSTUDY

Query Activities Trending Toward Timeout

Find Query Activities whose average runtime is already entering the danger zone.

sqlquery activitytimeoutactivitytype
MobileConnectPRODUCTION

SMS Tracking by Journey Version

Map Journey-sent SMS tracking records to the Journey version via JBDefinitionID.

sqlsmsmobileconnectjourney
MobileConnectPRODUCTION

Recent MobileConnect Opt-Outs

Review recently logged SMS opt-outs without assuming every row has a SubscriberKey.

sqlsmsoptoutsubscription
MobileConnectPRODUCTION

Held / Undeliverable Mobile Numbers

Inspect MobileConnect numbers that are held after repeated delivery failures.

sqlsmsundeliverablebounce
DeliverabilityPRODUCTION

Bounce Concentration by Domain & Category

Aggregate recent bounce evidence before deciding whether an issue is recipient-level, domain-specific or broader.

sqlbouncedomaindeliverability
DeliverabilityPRODUCTION

Review Held / Bounced Subscriber State

Inspect current All Subscribers state and bounce count for non-active records.

sqlsubscribersheldbounce
AMPscriptPRODUCTION

Defensive AttributeValue() + Empty() Fallback

Read a send-context attribute without assuming the field always exists or contains a value.

ampscriptattributevalueemptyfallback
AMPscriptPRODUCTION

Bounded LookupOrderedRows()

Retrieve a small, ordered rowset instead of scanning an unbounded one-to-many relationship at render time.

ampscriptlookuporderedrowsrowcountperformance
AMPscriptSTUDY

RaiseError() for a Broken Recipient, Not Segmentation

Abort only the current recipient when a genuine rendering invariant is violated.

ampscriptraiseerrorerror handling
CloudPagesPROJECT

CloudPagesURL() with Encrypted Parameters

Pass customer context from email to a CloudPage using Salesforce encrypted query-string handling.

ampscriptcloudpagesurlencrypted paramscloudpages
CloudPagesPROJECT

Validate CloudPage Request Parameters Before Writes

Gate state-changing CloudPage logic behind explicit input and record validation.

cloudpagesrequestparametervalidationsecurity
CloudPagesPROJECT

CloudPage Upsert Instead of Blind Insert

Use a stable key so refresh/retry does not blindly append duplicate state rows.

cloudpagesupsertdataidempotencydata extension
SSJS / WSProxyPROJECT

WSProxy Retrieve All Pages

Retrieve every page from a WSProxy SOAP object instead of silently stopping at the first batch.

ssjswsproxyretrievepagination
SSJS / WSProxyPROJECT

Inspect WSProxy updateBatch() Results

Treat a batch call result as data to validate rather than assuming “no exception” means every row succeeded.

ssjswsproxyupdatebatcherror handling
REST APILAB

OAuth Token Cache Pattern

Reuse Marketing Cloud access tokens instead of creating a new token for every API request.

apioauthtokencache
REST APILAB

429 + Retry-After Exponential Backoff

Back off when SFMC rate-limits a route instead of hammering it with immediate retries.

api429retry-afterbackoff
Journey BuilderPRODUCTION

Journey Email Sends in the Last 24 Hours

See recent Journey email sends with Journey/version/activity context.

sqljourneysent24h
Automation HealthPROJECT

Automation Runtime Regression — Current vs 30-Day Average

Compare each automation’s most recent duration with its recent average to find successful-but-degrading flows.

sqlautomationruntimeregression
DockerLAB

Docker Compose Healthcheck — Fail Closed on Dependency Readiness

Expose service readiness as health state instead of assuming a started container is usable.

dockercomposehealthcheckoperations
DockerLAB

Docker Compose — Explicit Persistent Volume

Make application state survive container recreation by declaring storage outside the writable container layer.

dockercomposevolumepersistence
LinuxLAB

systemd Unit for a Docker Compose Stack

Bring a self-hosted Compose stack up after boot and shut it down cleanly with the host.

linuxsystemddockerboot
n8nLAB

n8n Webhook — Stable Error Envelope

Return predictable success/error response shapes so callers can distinguish accepted input from workflow failure.

n8nwebhookapierror handling
Webhook SecuritySTUDY

Webhook HMAC Verification — Canonical Pattern

Verify that an inbound webhook body was signed by the expected sender before processing side effects.

webhookhmacsecuritysignature
SecretsSTUDY

Load Secrets from Environment — Keep Them Out of Git

Read runtime secrets from environment/configuration rather than embedding credentials in versioned source.

securitysecretsenvironment variablesgit
PythonPROJECT

Python — Shallow Snapshot Schema Diff

Compare normalized object dictionaries to identify keys that were added, removed or changed between exports.

pythonsnapshotdiffmetadata
LLM EngineeringSTUDY

LLM Review — Bounded Context + Provenance Prompt

Constrain an AI review to supplied context and require explicit separation between documented facts, observations and inference.

llmcontextprovenancereview