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.
Deterministic Deduplication — Latest Record
Keep the most recent row for each logical identity using ROW_NUMBER().
Anti-Join / Exclusion Audience
Find records in a source population that do not have a qualifying event or membership.
Latest Version per Journey
Return only the highest version number for each JourneyID and optionally exclude inactive states.
Journey → Activity → Email Tracking
Map email tracking events back to Journey Builder journey and activity names.
Find Job IDs for Journey Email Activities
Resolve Journey Builder email activities to their JobID values for reporting and troubleshooting.
Subscriber Engagement — 120 Day Flags
Create recent-open/recent-click flags and last engagement dates for an audience.
Recent Bounce Diagnostics
Extract recent bounce category and SMTP details for deliverability investigation.
Current Email Subscriber Status
Read current All Subscribers status, bounce count and unsubscribe date from _Subscribers.
Random Audience Split with NTILE()
Randomly divide an eligible audience into similarly sized groups.
Incremental Window with Overlap
Reprocess a small overlap window so late-arriving records are not silently lost.
Defensive LookupRows()
Handle zero-row lookups explicitly before reading row fields.
Tracked Dynamic URL
Build a dynamic URL and preserve Marketing Cloud click tracking with RedirectTo().
Iterate JSON Arrays with BuildRowsetFromJson()
Convert a JSON array into a rowset and iterate it in AMPscript.
Encrypted CloudPagesURL Parameters
Pass subscriber/context values to a CloudPage without exposing raw query parameters.
CloudPage — Read & Validate Request Parameters
Read request parameters and reject missing required identity context.
SSJS HTTP POST Webhook
Send a JSON payload to an external webhook from a Script Activity.
WSProxy Retrieve with Pagination
Retrieve SOAP objects beyond a single response page using RequestID / getNextBatch().
WSProxy DataExtensionObject UpdateAdd Batch
Batch upsert Data Extension rows through the SOAP object model.
Email HTML — Minimal Defensive Shell
Baseline email markup with viewport, dark-mode metadata and Outlook DPI handling.
n8n Public Webhook Contract
Small public webhook contract for portfolio/contact workflows with explicit validation boundaries.
Docker Compose — Service Baseline
A small baseline for restart policy, health checks and environment-file separation.
Never Hardcode Secrets in SFMC Scripts
Audit Script Activities and Content Builder assets for embedded credentials and tokens.
Python — Normalize Extracted Metadata
Normalize inconsistent metadata keys into a stable schema before reporting/export.
LLM Assistance — Constrain Output to a Schema
Use explicit schemas and validation when AI assists with repeatable engineering work.
ROW_NUMBER() with a Deterministic Tie-Breaker
Make deduplication deterministic when the main timestamp can tie.
ROW_NUMBER() with Business Priority
Choose a surviving customer row by source trust first, recency second.
Second Most Recent Record per Key
Use ROW_NUMBER() as a history/debugging tool, not only for rn = 1.
SARGable Rolling Date Window
Filter recent Data View rows without wrapping the source date column in a function.
Pre-Aggregate Tracking Before Joining
Reduce event grain before combining behavior tables.
First Unique Open in a Window
Return the first unique open date per subscriber within a defined analysis window.
Latest Unique Click per Subscriber
Collapse click tracking to one latest engagement timestamp per subscriber.
COALESCE() for Ordered Fallback Values
Choose the first non-null value from multiple candidate fields.
CASE-Based Business Segmentation
Translate explicit business rules into a readable segment label.
UNION ALL for Multi-Source Staging
Normalize multiple source populations into one staging shape without deduplicating too early.
Fast Approximate Split with _CustomObjectKey Modulo
Use the hidden row key for cheap approximate segmentation of a standard Data Extension.
TOP + ORDER BY for a Limited Ordered Set
Select a limited number of rows using SQL Server-style TOP syntax.
Explicit Column Contract — No SELECT *
Promote production queries with explicit output columns instead of SELECT *.
Stage Before Large Add/Update
Move expensive transformation into an overwrite staging DE before a large Add/Update write.
Latest Run Status per Automation
Return the latest known Automation Studio run for each AutomationCustomerKey.
Automation Failures / Skips in the Last 24h
Surface recent unhealthy Automation Studio runs with the first error detail.
Automation Activity Runtime & Error Health
Measure average activity runtime and failure count by activity key.
Query Activities Trending Toward Timeout
Find Query Activities whose average runtime is already entering the danger zone.
SMS Tracking by Journey Version
Map Journey-sent SMS tracking records to the Journey version via JBDefinitionID.
Recent MobileConnect Opt-Outs
Review recently logged SMS opt-outs without assuming every row has a SubscriberKey.
Held / Undeliverable Mobile Numbers
Inspect MobileConnect numbers that are held after repeated delivery failures.
Bounce Concentration by Domain & Category
Aggregate recent bounce evidence before deciding whether an issue is recipient-level, domain-specific or broader.
Review Held / Bounced Subscriber State
Inspect current All Subscribers state and bounce count for non-active records.
Defensive AttributeValue() + Empty() Fallback
Read a send-context attribute without assuming the field always exists or contains a value.
Bounded LookupOrderedRows()
Retrieve a small, ordered rowset instead of scanning an unbounded one-to-many relationship at render time.
RaiseError() for a Broken Recipient, Not Segmentation
Abort only the current recipient when a genuine rendering invariant is violated.
CloudPagesURL() with Encrypted Parameters
Pass customer context from email to a CloudPage using Salesforce encrypted query-string handling.
Validate CloudPage Request Parameters Before Writes
Gate state-changing CloudPage logic behind explicit input and record validation.
CloudPage Upsert Instead of Blind Insert
Use a stable key so refresh/retry does not blindly append duplicate state rows.
WSProxy Retrieve All Pages
Retrieve every page from a WSProxy SOAP object instead of silently stopping at the first batch.
Inspect WSProxy updateBatch() Results
Treat a batch call result as data to validate rather than assuming “no exception” means every row succeeded.
OAuth Token Cache Pattern
Reuse Marketing Cloud access tokens instead of creating a new token for every API request.
429 + Retry-After Exponential Backoff
Back off when SFMC rate-limits a route instead of hammering it with immediate retries.
Journey Email Sends in the Last 24 Hours
See recent Journey email sends with Journey/version/activity context.
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.
Docker Compose Healthcheck — Fail Closed on Dependency Readiness
Expose service readiness as health state instead of assuming a started container is usable.
Docker Compose — Explicit Persistent Volume
Make application state survive container recreation by declaring storage outside the writable container layer.
systemd Unit for a Docker Compose Stack
Bring a self-hosted Compose stack up after boot and shut it down cleanly with the host.
n8n Webhook — Stable Error Envelope
Return predictable success/error response shapes so callers can distinguish accepted input from workflow failure.
Webhook HMAC Verification — Canonical Pattern
Verify that an inbound webhook body was signed by the expected sender before processing side effects.
Load Secrets from Environment — Keep Them Out of Git
Read runtime secrets from environment/configuration rather than embedding credentials in versioned source.
Python — Shallow Snapshot Schema Diff
Compare normalized object dictionaries to identify keys that were added, removed or changed between exports.
LLM Review — Bounded Context + Provenance Prompt
Constrain an AI review to supplied context and require explicit separation between documented facts, observations and inference.