Snowflake External Functions
SQL that reaches outside the warehouse
An external function is a SQL function whose implementation lives somewhere else â typically an AWS Lambda, an Azure Function, or a Google Cloud Function â and which Snowflake invokes over HTTPS through a proxy endpoint. The result comes back as rows, so a call that would normally require a bespoke Python service becomes a SELECT that sits inside a query, a view, or a scheduled task.
The capability is narrower than it first appears, and that narrowness is the design. External functions are for calling out to a remote service, not for running arbitrary compute inside the warehouse; the function body executes outside Snowflake, which means latency is network latency and availability is that of the remote endpoint. Treating them as an internal extension point â embedding business logic that should be a UDF â leads to systems that are slower and harder to reason about than the equivalent SQL.
- The API integration holds the cloud credentials and account allowlist.
- The proxy endpoint exposes a stable HTTPS path that Snowflake can call.
- The function maps that endpoint into a typed SQL signature.
Prerequisites
- !Snowflake roles and grants
- !Working knowledge of a serverless function service
What You'll Learn
- 1Assemble an API integration, proxy endpoint, and external function
- 2Shape request and response payloads for batched calls
- 3Scope access with grants, headers, and secrets
- 4Diagnose throttling, timeouts, and partial failures
The three objects that make a call work
External functions are assembled from three independently managed objects, and understanding what each one owns is most of the battle. The API integration stores the cloud role and the allowed gateway; the proxy endpoint is the addressable HTTPS resource on that gateway; the function is the SQL-visible object with arguments and a return type. Grants tie all three to the roles that may call or manage them.
| Object | Created by | Holds | Changes rarely |
|---|---|---|---|
| API integration | SECURITYADMIN | cloud role ARN, allowed gateways, API ID | yes, when accounts change |
| Proxy endpoint | cloud admin | URL, batch size, CORS, stage reference | yes, when routing changes |
| External function | SECURITYADMIN | SQL signature, server, context headers | no, on schema changes |
| Secret | SECURITYADMIN | header token value | yes, on rotation |
Keeping the endpoint separate from the function means the underlying cloud service can be redeployed â a new Lambda version, a moved gateway â without touching any SQL object, provided the endpoint URL stays the same. That separation is worth preserving in your deployment scripts rather than collapsing everything into one migration.
Creating the integration and endpoint
The cloud side must exist first: the gateway that fronts your function service, the policy that lets Snowflake invoke it, and a role for Snowflake to assume. Once that is in place, three SQL statements finish the wiring.
-- The cloud credentials Snowflake will assume
CREATE OR REPLACE API INTEGRATION api_weather
API_PROVIDER = aws_api_gateway
API_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/snowflake-external-fn'
API_ALLOWED_PREFIXES = ('https://abc123.execute-api.us-east-1.amazonaws.com/prod/')
ENABLED = TRUE
COMMENT = 'Weather enrichment service behind API Gateway';
-- The addressable proxy endpoint on that gateway
CREATE OR REPLACE API INTEGRATION api_weather_proxy
API_INTEGRATION = api_weather
API_CONTEXT = ('weather.enrich' => '/enrich')
COMMENT = 'Single context path for the weather function';
-- Inspect what was actually created
DESC API INTEGRATION api_weather;
SHOW API INTEGRATIONS LIKE 'api_weather%';
-- The SQL-visible function
CREATE OR REPLACE EXTERNAL FUNCTION weather.enrich(zip STRING, ts STRING)
RETURNS VARIANT
API_INTEGRATION = api_weather
MAX_BATCH_ROWS = 100
CONTEXT_HEADERS = (CURRENT_TIMESTAMP, CURRENT_USER, CURRENT_ROLE)
HEADER = ('x-api-key' => api_key_secret:api_key::STRING)
COMPRESSION = GZIP
COMMENT = 'Returns current conditions for a ZIP code';
-- Grant call permission
GRANT USAGE ON FUNCTION weather.enrich(STRING, STRING) TO ROLE ANALYST;
GRANT USAGE ON API INTEGRATION api_weather TO ROLE ANALYST;
MAX_BATCH_ROWS deserves attention because it changes the economics. Snowflake can combine rows from concurrent calls into a single HTTP request up to that limit, so a larger value amortises latency across many rows but also means a single failure affects more rows and the remote service sees bigger payloads. Start at fifty to one hundred and tune from observed call latency rather than guessing.
CONTEXT_HEADERS passes session metadata to the remote function, which is how the service can log who called it or apply per-user logic. CURRENT_TIMESTAMP, CURRENT_USER, and CURRENT_ROLE are the commonly useful ones, and the values arrive as standard HTTP headers your function can read.
Secrets and headers
Credentials should never appear inside the function definition. A secret object stores the value, the function references it by name, and the stored value is never returned by any SHOW or DESC command â only its fingerprint.
-- Store the credential the remote endpoint expects
CREATE OR REPLACE SECRET api_key_secret
TYPE = AUTHENTICATION
AUTHENTICATION_TYPE = BASIC_AUTH
USERNAME = 'snowflake'
PASSWORD = 'REDACTED';
-- Or a generic string secret for a custom header
CREATE OR REPLACE SECRET weather_token
TYPE = GENERIC_STRING
SECRET_STRING = 'prod-weather-token-2026';
CREATE OR REPLACE EXTERNAL FUNCTION weather.enrich2(zip STRING)
RETURNS VARIANT
API_INTEGRATION = api_weather
HEADER = ('x-token' => weather_token:token::STRING)
MAX_BATCH_ROWS = 100;
-- Rotation: replace the secret; the function definition is untouched
CREATE OR REPLACE SECRET weather_token
TYPE = GENERIC_STRING
SECRET_STRING = 'prod-weather-token-2026-q2';
GRANT READ ON SECRET weather_token TO ROLE SECURITYADMIN;
GRANT USAGE ON API INTEGRATION api_weather TO ROLE SECURITYADMIN;
-- What an operator can see about the secret
DESC SECRET weather_token;
Rotation is the payoff of this design. Replacing the secret object updates the value every function using it sees, with no ALTER FUNCTION and no redeploy of SQL â which removes the most common reason rotations get postponed.
Shaping the payload and reading the response
When you call an external function, Snowflake sends one row per record and batches them into a single HTTP request; the remote function returns a response array with one entry per input row, joined back by row_index. The remote side therefore sees a wrapper, not your bare arguments, and its own return value must itself be wrapped.
-- Simple call: the response is a table of JSON rows
SELECT
zip,
weather.enrich(zip, '2026-03-14T12:00:00Z'):temperature::FLOAT AS temp_f,
weather.enrich(zip, '2026-03-14T12:00:00Z'):conditions::STRING AS sky
FROM raw.stations
WHERE zip IS NOT NULL;
-- Batched enrichment inside a statement
WITH batch AS (
SELECT DISTINCT zip FROM raw.stations WHERE active
)
SELECT
b.zip,
w.value:temperature::FLOAT AS temp_f,
w.value:humidity::INTEGER AS humidity
FROM batch b,
LATERAL FLATTEN(input => weather.enrich(b.zip, TO_VARCHAR(CURRENT_DATE))) w;
-- Inside a view, so callers never see the transport details
CREATE OR REPLACE VIEW curated.stations_weather AS
SELECT
s.station_id,
s.zip,
s.lat,
s.lon,
e.value:temperature::FLOAT AS temp_f,
e.value:conditions::STRING AS conditions,
CURRENT_TIMESTAMP() AS enriched_at
FROM raw.stations s
LEFT JOIN LATERAL FLATTEN(
input => weather.enrich(s.zip, TO_VARCHAR(CURRENT_DATE))
) e ON TRUE;
Wrapping the call in a view is the single most useful pattern. It hides the flatten machinery from every downstream consumer, it gives you one place to apply the cast and the LEFT JOIN so a failed call yields NULL rather than dropping the row, and it means changing the remote service later is a CREATE OR REPLACE VIEW instead of a hunt through dashboards.
Error handling needs to be explicit because a batch is all-or-nothing at the HTTP level. ON_ERROR => 'CONTINUE' inside the remote function lets it return per-row errors in the response, which you can surface:
-- Surface remote errors alongside successful rows
SELECT
s.station_id,
e.value:temperature::FLOAT AS temp_f,
e.value:error::STRING AS remote_error
FROM raw.stations s,
LATERAL FLATTEN(input => weather.enrich(s.zip, TO_VARCHAR(CURRENT_DATE))) e
WHERE e.value:error IS NOT NULL
LIMIT 50;
-- Retry pattern: capture failures, re-run only those rows
CREATE OR REPLACE TEMPORARY TABLE weather_failures AS
SELECT station_id, zip
FROM raw.stations s
WHERE (SELECT COUNT(*) FROM LATERAL FLATTEN(
input => weather.enrich(s.zip, TO_VARCHAR(CURRENT_DATE)))
WHERE value:temperature IS NULL) > 0;
Batching, throttling, and failure modes
External calls fail in ways SQL functions do not, and each failure mode has a different signature. A cold-start timeout shows up as a blank result for the whole batch; throttling from the remote service appears as intermittent HTTP errors; a malformed response surfaces as JSON parse errors in your casts. Distinguishing them quickly is the skill worth building.
- Cold starts â the first call after idle latency can exceed the gateway timeout. Raise the remote function's provisioned concurrency rather than shortening the query.
- Throttling â the remote API rate-limits per account. Reduce
MAX_BATCH_ROWS, add a queue table between the query and the call, or raise the service quota. - Partial batches â one bad row can fail the whole call. Handle errors inside the remote function and return an error field.
- Schema drift â the remote service adds or renames a field. Cast defensively and monitor with a sampling query.
- Cost runaway â a join without a bound multiplies calls. Constrain the input with
DISTINCTor a row limit before calling.
The cost model is worth internalising: you pay for the warehouse time spent waiting on the network plus whatever the remote service charges. A query that calls out once per row on a billion-row table is an architectural error, not a tuning problem. When the volume genuinely requires per-row enrichment, the usual answer is to move the enrichment upstream into the pipeline rather than performing it at query time.
When to reach for something else
External functions are the right tool when the call is selective, the latency is tolerable, and the logic genuinely requires an external system. They are the wrong tool when the computation is expressible in SQL or Python inside Snowflake, when the call volume is unbounded, or when the remote service has no batch endpoint. Alternatives that usually win: a task that writes to a stage consumed by the remote service, a stored procedure that calls an external API through a driver, or pre-computing the enrichment during ingestion and joining it locally.
A useful test before committing: if your query plan contains more external calls than the underlying question has distinct keys, you have a fan-out problem and should deduplicate or pre-join first.
Mistakes that produce mysterious outages
Common Mistakes
Granting USAGE on the function without granting USAGE on the API integration
Fix: Both grants are required; the second one failing produces an error that names neither object clearly.
Embedding API keys as literals in the function definition
Fix: Store tokens in a secret object so rotation is an object replace and the value is never shown by DESC.
Calling the function once per row inside a wide join
Fix: Deduplicate the calling key first, or pre-compute enrichment into a table during ingestion.
Setting MAX_BATCH_ROWS too high to cut latency
Fix: Larger batches increase blast radius per failure and payload size; tune from measured latency instead.
Assuming a failed batch leaves partial results
Fix: HTTP-level failures fail the whole batch; return per-row errors from the remote function when partial success matters.
Letting the view expose the FLATTEN wrapper to every consumer
Fix: Wrap the call in a view with casts and LEFT JOIN semantics so callers see plain columns.
Not monitoring call duration separately from query duration
Fix: Break out external call time in query history so network latency is not mistaken for warehouse slowness.
Practices that keep external calls predictable
Best Practices
- Encapsulate every external call in a view with typed columns and NULL-on-failure behaviour.
- Deduplicate calling keys before the call so one row per distinct key reaches the endpoint.
- Store all credentials in secrets and rotate by replacing the secret object.
- Use CONTEXT_HEADERS so the remote service can attribute calls to users and roles.
- Monitor call counts and latency from query history and alert on sustained growth.
- Batch with a modest MAX_BATCH_ROWS and raise it only when measurements justify it.
- Keep the remote function idempotent so retries after a timeout are safe.
- Version the remote deployment independently of the SQL objects, using the stable endpoint URL.
Key takeaways
Key Takeaways
- External functions call a remote serverless endpoint and return its results as table rows.
- Three objects compose the path: API integration, proxy endpoint, and the SQL function.
- Secrets hold credentials so rotation never requires editing the function definition.
- Responses are arrays joined by row_index, so flatten and cast inside a view.
- Batch failures are typically all-or-nothing at the HTTP layer; handle errors remotely.
- Volume is the constraint: per-row calls at scale belong upstream, not in the query.
- Wrapping the call in a view is the pattern that makes the whole feature maintainable.
Where to go next
- Data Quality â validating enriched results before they feed downstream models.
- Tasks Advanced â scheduling external enrichment in a controlled pipeline.
- Security Best Practices â secrets, network policies, and integration hygiene.
- Monitoring Queries â breaking out external call time from warehouse time.