Tip Try Routine Load out in this Quick Start This topic introduces how to create a Routine Load job to stream Kafka messages (events) into the database, and familiarizes you with some basic concepts about Routine Load. To continuously load messages of a stream into the database, you can store the message stream in a Kafka topic, and create a Routine Load job to consume the messages. The Routine Load job persists in the database, generates a series of load tasks to consume the messages in all or part of the partitions in the topic, and loads the messages into the database. A Routine Load job supports exactly-once delivery semantics to guarantee the data loaded into the database is neither lost nor duplicated. Routine Load supports data transformation at data loading and supports data changes made by UPSERT and DELETE operations during data loading. For more information, see Transform data at loading and Change data through loading.
You can load data into tables only as a user who has the INSERT privilege on those tables. If you do not have the INSERT privilege, follow the instructions provided in GRANT to grant the INSERT privilege to the user that you use to connect to your cluster. The syntax is
GRANT INSERT ON TABLE <table_name> IN DATABASE <database_name> TO { ROLE <role_name> | USER <user_identity>}.
Supported data formats
Routine Load now supports consuming CSV, JSON, and Avro (supported since v3.0.1) formatted data from a Kafka cluster.NOTE For CSV data, take note of the following points:
- You can use a UTF-8 string, such as a comma (,), tab, or pipe (|), whose length does not exceed 50 bytes as a text delimiter.
- Null values are denoted by using
\N. For example, a data file consists of three columns, and a record from that data file holds data in the first and third columns but no data in the second column. In this situation, you need to use\Nin the second column to denote a null value. This means the record must be compiled asa,\N,binstead ofa,,b.a,,bdenotes that the second column of the record holds an empty string.
Basic concepts

Terminology
- Load job A Routine Load job is a long-running job. As long as its status is RUNNING, a load job continuously generates one or multiple concurrent load tasks which consume the messages in a topic of a Kafka cluster and load the data into the database.
- Load task A load job is split into multiple load tasks by certain rules. A load task is the basic unit of data loading. As an individual event, a load task implements the load mechanism based on Stream Load. Multiple load tasks concurrently consume the messages from different partitions of a topic, and load the data into the database.
Workflow
- Create a Routine Load job. To load data from Kafka, you need to create a Routine Load job by running the CREATE ROUTINE LOAD statement. The FE parses the statement, and creates the job according to the properties you have specified.
-
The FE splits the job into multiple load tasks.
The FE split the job into multiple load tasks based on certain rules. Each load task is an individual transaction.
The splitting rules are as follows:
- The FE calculates the actual concurrent number of the load tasks according to the desired concurrent number
desired_concurrent_number, the partition number in the Kafka topic, and the number of the BE nodes that are alive. - The FE splits the job into load tasks based on the actual concurrent number calculated, and arranges the tasks in the task queue.
- A partition is uniquely assigned to a load task, and all messages from the partition are consumed by the load task.
- A load task can consume messages from one or more partitions.
- All partitions are distributed evenly among load tasks.
- The FE calculates the actual concurrent number of the load tasks according to the desired concurrent number
-
Multiple load tasks run concurrently to consume the messages from multiple Kafka topic partitions, and load the data into the database
-
The FE schedules and submits load tasks: the FE schedules the load tasks in the queue on a timely basis, and assigns them to selected Coordinator BE nodes. The interval between load tasks is defined by the configuration item
max_batch_interval. The FE distributes the load tasks evenly to all BE nodes. See CREATE ROUTINE LOAD for more information aboutmax_batch_interval. -
The Coordinator BE starts the load task, consumes messages in partitions, parses and filters the data. A load task lasts until the pre-defined amount of messages are consumed or the pre-defined time limit is reached. The message batch size and time limit are defined in the FE configurations
max_routine_load_batch_sizeandroutine_load_task_consume_second. For detailed information, see FE Configuration. The Coordinator BE then distributes the messages to the Executor BEs. The Executor BEs write the messages to disks.NOTE StarRocks supports access to Kafka via security protocols including SASL_SSL, SAS_PLAINTEXT, SSL, and PLAINTEXT. This topic uses connecting to Kafka via PLAINTEXT as an example. If you need to connect to Kafka via other security protocols, see CREATE ROUTINE LOAD.
-
The FE schedules and submits load tasks: the FE schedules the load tasks in the queue on a timely basis, and assigns them to selected Coordinator BE nodes. The interval between load tasks is defined by the configuration item
- The FE generates new load tasks to load data continuously. After the Executor BEs has written the data to disks, the Coordinator BE reports the result of the load task to the FE. Based on the result, the FE then generates new load tasks to load the data continuously. Or the FE retries the failed tasks to make sure the data loaded into the database is neither lost nor duplicated.
Create a Routine Load job
The following three examples describe how to consume CSV-format, JSON-format and Avro-format data in Kafka, and load the data into the database by creating a Routine Load job. For detailed syntax and parameter descriptions, see CREATE ROUTINE LOAD.Load CSV-format data
This section describes how to create a Routine Load job to consume CSV-format data in a Kafka cluster, and load the data into the database.Prepare a dataset
Suppose there is a CSV-format dataset in the topicordertest1 in a Kafka cluster. Every message in the dataset includes six fields: order ID, payment date, customer name, nationality, gender, and price.
Create a table
According to the fields of CSV-format data, create the tableexample_tbl1 in the database example_db. The following example creates a table with 5 fields excluding the field of customer gender in the CSV-format data.
NOTICE Since v2.5.7, the database can automatically set the number of buckets (BUCKETS) when you create a table or add a partition. You no longer need to manually set the number of buckets. For detailed information, see set the number of buckets.
Submit a Routine Load job
Execute the following statement to submit a Routine Load job namedexample_tbl1_ordertest1 to consume the messages in the topic ordertest1 and load the data into the table example_tbl1. The load task consumes the messages from the initial offset in the specified partitions of the topic.
- load job name There could be multiple load job on a table. Therefore, we recommend you name a load job with the corresponding Kafka topic and the time when the load job is submitted. It helps you distinguish the load job on each table.
-
Column separator
The property
COLUMN TERMINATED BYdefines the column separator of the CSV-format data. The default is\t. -
Kafka topic partition and offset
You can specify the properties
kafka_partitionsandkafka_offsetsto specify the partitions and offsets to consume the messages. For example, if you want the load job to consume messages from the Kafka partitions"0,1,2,3,4"of the topicordertest1all with the initial offsets, you can specify the properties as follows: If you want the load job to consume messages from the Kafka partitions"0,1,2,3,4"and you need to specify a separate starting offset for each partition, you can configure as follows:You can also set the default offsets of all partitions with the propertyproperty.kafka_default_offsets.For detailed information, see CREATE ROUTINE LOAD. -
Data mapping and transformation
To specify the mapping and transformation relationship between the CSV-format data, and the table, you need to use the
COLUMNSparameter. Data mapping:-
The database extracts the columns in the CSV-format data and maps them in sequence onto the fields declared in the
COLUMNSparameter. -
The database extracts the fields declared in the
COLUMNSparameter and maps them by name onto the columns of table.
temp_genderinCOLUMNSparameter is used as a placeholder for this field. The other fields are mapped to columns of the tableexample_tbl1directly. For more information about data transformation, see Transform data at loading.NOTE You do not need to specify the
COLUMNSparameter if the names, number, and order of the columns in the CSV-format data completely correspond to those of the StarRocks table. -
The database extracts the columns in the CSV-format data and maps them in sequence onto the fields declared in the
-
Task concurrency
When there are many Kafka topic partitions and enough BE nodes, you can accelerate the loading by increasing the task concurrency.
To increase the actual load task concurrency, you can increase the desired load task concurrency
desired_concurrent_numberwhen you create a routine load job. You can also set the dynamic configuration item of FEmax_routine_load_task_concurrent_num( default maximum load task currency ) to a larger value. For more information aboutmax_routine_load_task_concurrent_num, please see FE configuration items. The actual task concurrency is defined by the minimum value among the number of BE nodes that are alive, the number of the pre-specified Kafka topic partitions, and the values ofdesired_concurrent_numberandmax_routine_load_task_concurrent_num. In the example, the number of BE nodes that are alive is5, the number of the pre-specified Kafka topic partitions is5, and the value ofmax_routine_load_task_concurrent_numis5. To increase the actual load task concurrency, you can increase thedesired_concurrent_numberfrom the default value3to5. For more about the properties, see CREATE ROUTINE LOAD.
Load JSON-format data
This section describes how to create a Routine Load job to consume JSON-format data in a Kafka cluster, and load the data into the database.Prepare a dataset
Suppose there is a JSON-format dataset in the topicordertest2 in a Kafka cluster. The dataset includes six keys: commodity ID, customer name, nationality, payment time, and price. Besides, you want to transform the payment time column into the DATE type, and load it into the pay_dt column in the table.
CAUTION Each JSON object in a row must be in one Kafka message, otherwise a JSON parsing error is returned.
Create a table
According to the keys of the JSON-format data, create the tableexample_tbl2 in the database example_db.
NOTICE Since v2.5.7, the database can automatically set the number of buckets (BUCKETS) when you create a table or add a partition. You no longer need to manually set the number of buckets. For detailed information, see set the number of buckets.
Submit a Routine Load job
Execute the following statement to submit a Routine Load job namedexample_tbl2_ordertest2 to consume the messages in the topic ordertest2 and load the data into the table example_tbl2. The load task consumes the messages from the initial offset in the specified partitions of the topic.
-
Data format
You need to specify
"format" = "json"in the clausePROPERTIESto define that the data format is JSON. -
Data mapping and transformation
To specify the mapping and transformation relationship between the JSON-format data, and the table, you need to specify the parameter
COLUMNSand propertyjsonpaths. The order of fields specified in theCOLUMNSparameter must match that of the JSON-format data, and the name of fields must match that of the table. The propertyjsonpathsis used to extract the required fields from the JSON data. These fields are then named by the propertyCOLUMNS. Because the example needs to transform the payment time field to the DATE data type, and load the data into thepay_dtcolumn in the table, you need to use the from_unixtime function. The other fields are mapped to fields of the tableexample_tbl2directly. Data mapping:-
The database extracts the
nameandcodekeys of JSON-format data and maps them onto the keys declared in thejsonpathsproperty. -
The database extracts the keys declared in the
jsonpathsproperty and maps them in sequence onto the fields declared in theCOLUMNSparameter. -
The database extracts the fields declared in the
COLUMNSparameter and maps them by name onto the columns of table.
-
Because the example needs to transform the key
pay_timeto the DATE data type, and load the data into thepay_dtcolumn in the table, you need to use the from_unixtime function inCOLUMNSparameter. The other fields are mapped to fields of the tableexample_tbl2directly. -
And because the example excludes the column of customer gender from the JSON-format data, the field
temp_genderinCOLUMNSparameter is used as a placeholder for this field. The other fields are mapped to columns of the tableexample_tbl1directly. For more information about data transformation, see Transform data at loading.NOTE You do not need to specify the
COLUMNSparameter if the names and number of the keys in the JSON object completely match those of fields in the StarRocks table.
-
The database extracts the
Load Avro-format data
Since v3.0.1, the database supports loading Avro data by using Routine Load.Prepare a dataset
Avro schema
-
Create the following Avro schema file
avro_schema.avsc: - Register the Avro schema in the Schema Registry.
Avro data
Prepare the Avro data and send it to the Kafka topictopic_0.
Create a table
According to the fields of Avro data, create a tablesensor_log in the target database example_db in the cluster. The column names of the table must match the field names in the Avro data. For the data type mapping between the table columns and the Avro data fields, see [Data types mapping](#Data types mapping).
NOTICE Since v2.5.7, the database can automatically set the number of buckets (BUCKETS) when you create a table or add a partition. You no longer need to manually set the number of buckets. For detailed information, see set the number of buckets.
Submit a Routine Load job
Execute the following statement to submit a Routine Load job namedsensor_log_load_job to consume the Avro messages in the Kafka topic topic_0 and load the data into the table sensor_log in the database sensor. The load job consumes the messages from the initial offset in the specified partitions of the topic.
-
Data Format
You need to specify
"format = "avro"in the clausePROPERTIESto define that the data format is Avro. -
Schema Registry
You need to configure
confluent.schema.registry.urlto specify the URL of the Schema Registry where the Avro schema is registered. The database retrieves the Avro schema by using this URL. The format is as follows: -
Data mapping and transformation
To specify the mapping and transformation relationship between the Avro-format data and the table, you need to specify the parameter
COLUMNSand propertyjsonpaths. The order of fields specified in theCOLUMNSparameter must match that of the fields in the propertyjsonpaths, and the names of fields must match these of the table. The propertyjsonpathsis used to extract the required fields from the Avro data. These fields are then named by the propertyCOLUMNS. For more information about data transformation, see Transform data at loading.NOTE You do not need to specify the
COLUMNSparameter if the names and number of the fields in the Avro record completely match those of columns in the table.
Data types mapping
The data type mapping between the Avro data fields you want to load and the table columns is as follows:Primitive types
Complex types
Limits
- Currently, the database does not support schema evolution.
- Each Kafka message must only contain a single Avro data record.
Access source message metadata
When loading JSON- or Avro-format data, you can populate destination columns from a messageās Kafka/Pulsar metadata ā topic, partition, offset, timestamp, key, and headers ā instead of from the message payload. You declare the metadata in anINCLUDE METADATA (...) clause that binds each metadata key to an alias; the alias is an ordinary source column you reference from COLUMNS.
This is useful for auditing (which topic/partition/offset a row came from), event-time processing (using the message timestamp), and routing on a header value.
Syntax
INCLUDE METADATA is a load property; place it among the other load properties (such as COLUMNS and WHERE), in any order, before the PROPERTIES and FROM clauses. AS <alias> is optional. If it is omitted, the alias defaults to <metadata_key>. The alias must be unique within the clause, and it must not collide with a payload field, a destination-table column, or a reserved column name.
Metadata keys
The supported keys depend on the data source.
To read a single header/property value, use
element_at(<headers_alias>, '<name>') over the HEADERS/PROPERTIES map: the last value wins on a duplicate key, and the result is NULL when the key is absent. Header/property values are raw bytes placed into VARCHAR as-is (no UTF-8 validation).
Usage notes
INCLUDE METADATAis available forformat = json(Kafka and Pulsar) andformat = avro(Kafka only; Pulsar Routine Load does not support Avro). It is not supported for CSV, where one message can expand into many rows and per-message metadata would be ambiguous.- A metadata alias is an ordinary source column: reference it anywhere in the
COLUMNSexpressions. If a payload field has the same name as a metadata key, specify a different alias withAS <alias>to avoid ambiguity. OFFSETis Kafka-only andMESSAGE_IDis Pulsar-only; using a key unsupported by the source raises an error that lists the keys supported for that source.HEADERS/PROPERTIESis aMAP\<VARCHAR, VARCHAR>. The source headers/properties are an ordered list that may repeat a key; duplicates collapse into the map with the last value winning (anelement_at(map, 'name')lookup is likewise last-wins, and returnsNULLwhen the key is absent). Values are raw bytes stored in VARCHAR as-is ā there is no UTF-8 validation or decoding.
Example
Load the order payload fieldorder_id together with the source topic, partition, offset, the message timestamp converted to a DATETIME, and a trace-id header:
from_unixtime(m_timestamp / 1000) above); only payload columns are listed in jsonpaths.
Check a load job and task
Check a load job
Execute the SHOW ROUTINE LOAD statement to check the status of the load jobexample_tbl2_ordertest2. The database returns the execution state State, the statistical information (including the total rows consumed and the total rows loaded) Statistics, and the progress of the load job progress.
If the state of the load job is automatically changed to PAUSED, it is possibly because the number of error rows has exceeded the threshold. For detailed instructions on setting this threshold, see CREATE ROUTINE LOAD. You can check the files ReasonOfStateChanged and ErrorLogUrls to identify and troubleshoot the problem. Having fixed the problem, you can then execute the RESUME ROUTINE LOAD statement to resume the PAUSED load job.
If the state of the load job is CANCELLED, it is possibly because the load job encounters an exception (such as the table has been dropped). You can check the files ReasonOfStateChanged and ErrorLogUrls to identify and troubleshoot the problem. However, you cannot resume a CANCELLED load job.
CAUTION You cannot check a load job that has stopped or has not yet started.
Check a load task
Execute the SHOW ROUTINE LOAD TASK statement to check the load tasks of the load jobexample_tbl2_ordertest2, such as how many tasks are currently running, the Kafka topic partitions that are consumed and the consumption progress DataSourceProperties, and the corresponding Coordinator BE node BeId.
Pause a load job
You can execute the PAUSE ROUTINE LOAD statement to pause a load job. The state of the load job will be PAUSED after the statement is executed. However, it has not stopped. You can execute the RESUME ROUTINE LOAD statement to resume it. You can also check its status with the SHOW ROUTINE LOAD statement. The following example pauses the load jobexample_tbl2_ordertest2:
Resume a load job
You can execute the RESUME ROUTINE LOAD statement to resume a paused load job. The state of the load job will be NEED_SCHEDULE temporarily (because the load job is being re-scheduled), and then become RUNNING. You can check its status with the SHOW ROUTINE LOAD statement. The following example resumes the paused load jobexample_tbl2_ordertest2:
Alter a load job
Before altering a load job, you must pause it with the PAUSE ROUTINE LOAD statement. Then you can execute the ALTER ROUTINE LOAD. After altering it, you can execute the RESUME ROUTINE LOAD statement to resume it, and check its status with the SHOW ROUTINE LOAD statement. Suppose the number of the BE nodes that are alive increases to6 and the Kafka topic partitions to be consumed is "0,1,2,3,4,5,6,7". If you want to increase the actual load task concurrency, you can execute the following statement to increase the number of desired task concurrency desired_concurrent_number to 6 (greater than or equal to the number of BE nodes that are alive), and specify the Kafka topic partitions and initial offsets.
NOTE Because the actual task concurrency is determined by the minimum value of multiple parameters, you must make sure that the value of the FE dynamic parametermax_routine_load_task_concurrent_numis greater than or equal to6.
Stop a load job
You can execute the STOP ROUTINE LOAD statement to stop a load job. The state of the load job will be STOPPED after the statement is executed, and you cannot resume a stopped load job. You cannot check the status of a stopped load job with the SHOW ROUTINE LOAD statement. The following example stops the load jobexample_tbl2_ordertest2: