Est.

Guide

Snowflake Tasks Guide: Schedules, Task Graphs, Monitoring and Cost

How Snowflake tasks work: serverless or warehouse compute, interval and CRON schedules, triggered tasks, task graphs with finalizers, privileges, failure handling and retries, monitoring with TASK_HISTORY, and what tasks cost.

Data Cloud Weekly Editors · Updated

A task is Snowflake's built-in scheduler. It runs one SQL statement, a call to a stored procedure, or a block of Snowflake Scripting, on a schedule, when a stream has new data, or after other tasks finish. Chained together, tasks become a task graph: a small orchestrator that lives inside the warehouse, with no external scheduler to run. This guide covers the two ways a task gets compute, how to schedule and trigger it, building a task graph, the privileges it needs, what happens when it fails, how to watch it, and what it costs.

Creating your first task

CREATE TASK analytics.core.refresh_daily_orders
  WAREHOUSE = transform_wh
  SCHEDULE = 'USING CRON 15 2 * * * UTC'
  COMMENT = 'Rebuild daily order totals'
AS
  INSERT OVERWRITE INTO analytics.core.daily_orders
  SELECT order_date, COUNT(*), SUM(total)
  FROM analytics.core.orders
  GROUP BY order_date;

-- New tasks are created suspended
ALTER TASK analytics.core.refresh_daily_orders RESUME;

Three things catch people out the first time:

  • Tasks start suspended. CREATE TASK, CREATE OR REPLACE TASK and cloning all leave the task suspended. Nothing runs until ALTER TASK ... RESUME.
  • Test it before you schedule it. EXECUTE TASK analytics.core.refresh_daily_orders; runs it once, even while it is suspended. Run the body by hand as the task's owner role first, too: the task runs with that role's privileges, not yours.
  • Autocommit must be on. A task fails if AUTOCOMMIT is FALSE, and SEARCH_PATH can't be set for a task. To run several statements as one unit, wrap them in an explicit transaction, for example inside a stored procedure the task calls.

Serverless or your own warehouse

Name a WAREHOUSE and the task runs on it. Leave it out and the task is serverless: Snowflake picks the compute size for each run from the history of recent runs.

-- Serverless, with bounds on how big Snowflake may go
CREATE TASK raw.load_events
  SCHEDULE = '10 MINUTES'
  USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'SMALL'
  SERVERLESS_TASK_MIN_STATEMENT_SIZE = 'XSMALL'
  SERVERLESS_TASK_MAX_STATEMENT_SIZE = 'LARGE'
AS
  CALL raw.load_events_proc();
ServerlessUser-managed warehouse
SizingSnowflake sizes each run, from XSMALL up to the equivalent of XXLARGE, within the min and max you setYou choose the size, and share or dedicate the warehouse
Billed onCompute actually used by the runsWarehouse time while it runs, with a 60-second minimum each time it resumes
Fits bestShort or steady tasks that would leave a warehouse mostly idle; tight schedulesWarehouses already busy with other work; heavy or unpredictable loads; runs that must not fail
Extra privilegeEXECUTE MANAGED TASK on the accountUSAGE on the warehouse

Snowflake's own guidance has one more distinction worth knowing: serverless tasks run on shared compute, and a run can occasionally be interrupted and fail with an internal error. Most statements are retried automatically, but a task that runs CALL on a stored procedure is not, so the failure reaches you. For loads that can't safely be rerun, Snowflake recommends a user-managed task on a dedicated warehouse. If a warehouse task's run is short and the warehouse otherwise idle, its auto-suspend setting decides much of the cost; our piece on auto-suspend and auto-resume tuning goes through that.

Schedules: intervals and CRON

SCHEDULE takes either a fixed interval or a CRON expression with a time zone:

SCHEDULE = '5 MINUTES'                               -- also SECONDS or HOURS
SCHEDULE = 'USING CRON 0 6 * * MON-FRI Europe/London'  -- 06:00 on weekdays
SCHEDULE = 'USING CRON 30 1 L * * UTC'                 -- 01:30 on the last day of the month

The CRON fields are minute, hour, day of month, month and day of week, and Snowflake supports a subset of standard cron syntax (including L for "last"). Always give an explicit time zone; a CRON schedule in a zone with daylight saving can skip or repeat a run on the night the clocks change, so schedule critical jobs in UTC or away from the changeover hour. Snowflake's examples also suggest an odd minute (7, 24, 34) rather than 0, so your tasks don't all start at once.

A scheduled task never runs on top of itself: if a run is still going when the next one is due, that scheduled run is skipped. Only a standalone task or the root of a task graph can have a schedule. A task with no schedule and no trigger runs only when someone calls EXECUTE TASK.

Triggered tasks and WHEN conditions

A task can run when a stream has new data instead of on a clock. Leave out SCHEDULE and give a WHEN condition on the stream:

CREATE TASK core.apply_order_changes
  WAREHOUSE = transform_wh
  WHEN SYSTEM$STREAM_HAS_DATA('raw.orders_stream')
AS
  INSERT INTO core.orders_log
  SELECT order_id, status, METADATA$ACTION
  FROM raw.orders_stream;

A triggered task runs at most every 30 seconds by default (USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS, minimum 10); changes that arrive faster are processed together. A serverless triggered task also needs TARGET_COMPLETION_INTERVAL. You can combine both styles: a SCHEDULE plus a WHEN clause checks on the schedule and skips the run when there is nothing to do.

Checking WHEN uses no warehouse; it is evaluated in the cloud services layer, with a small charge for each check that doesn't lead to a run. The body has to consume the stream in a DML statement every time it runs, or the stream keeps reporting data and the task keeps running. Our Snowflake streams guide covers offsets, the merge pattern and keeping a stream from going stale.

Task graphs: AFTER, finalizers and return values

A task graph starts at a root task with a schedule; every other task names its predecessors with AFTER and runs once all of them have succeeded. Tasks in one graph must live in the same schema and have the same owner role.

CREATE TASK etl.root
  WAREHOUSE = transform_wh
  SCHEDULE = 'USING CRON 20 3 * * * UTC'
  CONFIG = '{"env": "prod"}'
AS
  CALL etl.start_batch();

CREATE TASK etl.load_customers AFTER etl.root AS CALL etl.load('customers');
CREATE TASK etl.load_orders    AFTER etl.root AS CALL etl.load('orders');

CREATE TASK etl.build_marts
  AFTER etl.load_customers, etl.load_orders
AS
  CALL etl.build_marts();

-- Runs after everything else, whether the graph succeeded or failed
CREATE TASK etl.wrap_up
  FINALIZE = etl.root
AS
  CALL etl.record_batch_result();

Child tasks have no schedule of their own and must be resumed too; a suspended child is skipped. The quickest way to resume a whole graph is one call:

SELECT SYSTEM$TASK_DEPENDENTS_ENABLE('etl.root');

To change any task in the graph (its SQL, or adding and removing AFTER links), suspend the root first with ALTER TASK etl.root SUSPEND; the children don't need suspending individually.

A few tools make graphs more than a fixed chain:

  • Finalizer. A task created with FINALIZE = <root> runs after all other tasks complete or fail, which makes it the place for clean-up and a "batch finished" or "batch failed" message. Each root can have one, it can't have children, and it doesn't run when the root itself was skipped.
  • Return values. A task can call SYSTEM$SET_RETURN_VALUE('...'), and a child can read it with SYSTEM$GET_PREDECESSOR_RETURN_VALUE('TASK_NAME'), including in its WHEN clause, to skip a branch when, say, a validation step found nothing new. Task names here are case sensitive and stored in upper case when unquoted.
  • Config. CONFIG on the root holds a JSON object every task can read with SYSTEM$GET_TASK_GRAPH_CONFIG('env'), so the same graph can run against different paths or environments.
  • Overlap. OVERLAP_POLICY on the root decides whether a new graph run may start while the last is still going: NO_OVERLAP (the default), ALLOW_CHILD_OVERLAP or ALLOW_ALL_OVERLAP.

Snowflake documents the limits (predecessors and children per task, tasks per graph) in Create a sequence of tasks with a task graph.

Privileges and ownership

Tasks run as a system service with the privileges of the task's owner role, not as the person who created them, so a task keeps running when that person leaves. The owner role needs:

PrivilegeOnWhen
EXECUTE TASKAccountAlways, to run any task the role owns
EXECUTE MANAGED TASKAccountServerless tasks only
CREATE TASKSchemaTo create tasks there
USAGEDatabase, schema, warehouseWarehouse only for user-managed tasks

Plus whatever the task's own SQL needs. A common setup is a taskadmin role holding the account-level privileges, granted to each team role that owns tasks:

USE ROLE accountadmin;
CREATE ROLE taskadmin;
GRANT EXECUTE TASK, EXECUTE MANAGED TASK ON ACCOUNT TO ROLE taskadmin;
GRANT ROLE taskadmin TO ROLE transform_role;

A role with OPERATE on a task can suspend and resume it without owning it, which suits an on-call role. If the owner role is dropped, ownership passes to the role that dropped it and the task is paused until the new owner resumes it. Where row access or masking policies depend on who is querying, EXECUTE AS USER runs the task on behalf of a named (ideally service) user instead.

When a task fails

  • Timeouts. USER_TASK_TIMEOUT_MS caps a run; the default is one hour. On a graph's root it applies to the whole graph. Timed-out runs count as failures.
  • Automatic suspension. SUSPEND_TASK_AFTER_NUM_FAILURES (default 10) suspends a task, or a graph's root, after that many consecutive failed or timed-out runs, so a broken task stops spending credits. Set it lower for expensive tasks.
  • Automatic retries. TASK_AUTO_RETRY_ATTEMPTS on a root (off by default) reruns a failed graph from the task that failed.
  • Manual retry. EXECUTE TASK etl.root RETRY LAST; starts a new graph run at the last failed task(s), as long as the graph hasn't been changed since that run. EXECUTE TASK only accepts a standalone or root task, never a child.
  • Notifications. ERROR_INTEGRATION sends a message for each failed run to Amazon SNS, Azure Event Grid or Google Pub/Sub, through a notification integration on the same cloud as your account. Email and webhook integrations aren't accepted there; for those, Snowflake points to task alerts, or you can send a summary from a finalizer with SYSTEM$SEND_EMAIL. Snowflake describes the options in Set up alerts and notifications for tasks.

Replacing a task with CREATE OR REPLACE TASK leaves it suspended and cancels its next scheduled run, and for a serverless task it throws away the run history Snowflake sizes compute from. ALTER TASK, or CREATE OR ALTER TASK where your account supports it, keeps both.

Monitoring runs

For the last seven days, including the next scheduled run, use the TASK_HISTORY table function. It returns 100 rows unless you raise RESULT_LIMIT (up to 10,000):

SELECT name, state, scheduled_time, completed_time, error_message, return_value
FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY(
  SCHEDULED_TIME_RANGE_START => DATEADD(hour, -24, CURRENT_TIMESTAMP()),
  ERROR_ONLY => TRUE,
  RESULT_LIMIT => 1000))
ORDER BY scheduled_time DESC;

For a year of finished runs (succeeded, failed, cancelled or skipped), query SNOWFLAKE.ACCOUNT_USAGE.TASK_HISTORY; it can lag by up to 45 minutes. Comparing scheduled_time with query_start_time there shows how long runs wait for compute, a sign the warehouse they share is too busy. For graphs, CURRENT_TASK_GRAPHS shows runs scheduled or in progress and COMPLETE_TASK_GRAPHS recent finished ones. SHOW TASKS gives each task's state, schedule and predecessors, and Snowsight shows the same history as a graph.

What tasks cost

A task has no charge of its own; you pay for the compute its runs use. On a warehouse, that is the warehouse's normal credit usage while it runs, including the 60-second minimum each time it resumes, so a one-second task every minute can keep a warehouse awake all day. Serverless runs are billed on the compute they use, at the serverless task rate in Snowflake's Service Consumption Table. Skipped WHEN checks add a small cloud services charge.

SELECT task_name, DATE_TRUNC('day', start_time) AS day, SUM(credits_used) AS credits
FROM SNOWFLAKE.ACCOUNT_USAGE.SERVERLESS_TASK_HISTORY
WHERE start_time >= DATEADD(day, -30, CURRENT_TIMESTAMP())
GROUP BY 1, 2
ORDER BY credits DESC;

Your credit price depends on your contract, edition, cloud and region; check your Snowflake order form or the cost management pages in Snowsight rather than published list prices. Resource monitors only watch warehouses, so they don't see serverless tasks at all; a budget can alert on their spend. Our piece on resource monitors covers where that line falls.

Tasks or dynamic tables?

For a chain of SQL transformations where each table is just a query over the ones before it, dynamic tables are usually less to run: you declare the query and a target lag, and Snowflake works out the refresh order and schedule. Tasks stay the better fit when the work isn't a query result: calling procedures or external functions, loading or unloading files, sending notifications, writing several tables in one transaction, running at a fixed wall-clock time, or anything that needs branching on what an earlier step found. Our piece on dynamic tables for incremental pipelines compares the two in depth.

Common questions

Why didn't my task run?

Check, in order: that it (and, in a graph, every child) is resumed in SHOW TASKS; that it has a schedule or a trigger; that its WHEN condition was true; that the previous run had finished (otherwise the run is skipped); and that the owner role still has EXECUTE TASK. TASK_HISTORY shows skipped runs and the error of failed ones.

Can I run a child task on its own?

Not with EXECUTE TASK, which only accepts a standalone or root task. Run the child's SQL directly, or use RETRY LAST on the root if the child failed.

Does a suspended task lose its history?

No. Suspending and resuming keeps both the run history and, for serverless tasks, the sizing history. Recreating the task with CREATE OR REPLACE loses the sizing history.

Can two tasks read the same stream?

They can, but whichever consumes it first takes the changes. Give each task its own stream on the source table.

Related reading