Skip to main content

Amazon Kinesis ingestion

When you enable the Kinesis indexing service, you can configure supervisors on the Overlord to manage the creation and lifetime of Kinesis indexing tasks. These indexing tasks read events using Kinesis' own shard and sequence number mechanism to guarantee exactly-once ingestion. The supervisor oversees the state of the indexing tasks to coordinate handoffs, manage failures, and ensure that scalability and replication requirements are maintained.

This topic contains configuration reference information for the Kinesis indexing service supervisor for Apache Druid.


To use the Kinesis indexing service, you must first load the druid-kinesis-indexing-service core extension on both the Overlord and the Middle Manager. See Loading extensions for more information. Review the Kinesis known issues before deploying the druid-kinesis-indexing-service extension to production.

Supervisor spec

The following table outlines the high-level configuration options for the Kinesis supervisor object. See Supervisor API for more information.

typeStringThe supervisor type; this should always be kinesis.Yes
specObjectThe container object for the supervisor configuration.Yes
ioConfigObjectThe I/O configuration object for configuring Kinesis connection and I/O-related settings for the supervisor and indexing task.Yes
dataSchemaObjectThe schema used by the Kinesis indexing task during ingestion. See dataSchema for more information.Yes
tuningConfigObjectThe tuning configuration object for configuring performance-related settings for the supervisor and indexing tasks.No

Druid starts a new supervisor when you define a supervisor spec. To create a supervisor, send a POST request to the /druid/indexer/v1/supervisor endpoint. Once created, the supervisor persists in the configured metadata database. There can only be a single supervisor per datasource, and submitting a second spec for the same datasource overwrites the previous one.

When an Overlord gains leadership, either by being started or as a result of another Overlord failing, it spawns a supervisor for each supervisor spec in the metadata database. The supervisor then discovers running Kinesis indexing tasks and attempts to adopt them if they are compatible with the supervisor's configuration. If they are not compatible because they have a different ingestion spec or shard allocation, the tasks are killed and the supervisor creates a new set of tasks. In this way, the supervisors persist across Overlord restarts and failovers.

The following example shows how to submit a supervisor spec for a stream with the name KinesisStream. In this example, http://SERVICE_IP:SERVICE_PORT is a placeholder for the server address of deployment and the service port.

curl -X POST "http://SERVICE_IP:SERVICE_PORT/druid/indexer/v1/supervisor" \
-H "Content-Type: application/json" \
-d '{
"type": "kinesis",
"spec": {
"ioConfig": {
"type": "kinesis",
"stream": "KinesisStream",
"inputFormat": {
"type": "json"
"useEarliestSequenceNumber": true
"tuningConfig": {
"type": "kinesis"
"dataSchema": {
"dataSource": "KinesisStream",
"timestampSpec": {
"column": "timestamp",
"format": "iso"
"dimensionsSpec": {
"dimensions": [
"type": "long",
"name": "added"
"type": "long",
"name": "commentLength"
"type": "long",
"name": "delta"
"type": "long",
"name": "deltaBucket"
"type": "long",
"name": "deleted"
"granularitySpec": {
"queryGranularity": "none",
"rollup": false,
"segmentGranularity": "hour"

Supervisor I/O configuration

The following table outlines the configuration options for ioConfig:

streamStringThe Kinesis stream to read.Yes
inputFormatObjectThe input format to specify how to parse input data. See Specify data format for more information.Yes
endpointStringThe AWS Kinesis stream endpoint for a region. You can find a list of endpoints in the AWS service endpoints
replicasIntegerThe number of replica sets, where 1 is a single set of tasks (no replication). Druid always assigns replicate tasks to different workers to provide resiliency against process failure.No1
taskCountIntegerThe maximum number of reading tasks in a replica set. Multiply taskCount and replicas to measure the maximum number of reading tasks.
The total number of tasks (reading and publishing) is higher than the maximum number of reading tasks. See Capacity planning for more details. When taskCount > {numKinesisShards}, the actual number of reading tasks is less than the taskCount value.
taskDurationISO 8601 periodThe length of time before tasks stop reading and begin publishing their segments.NoPT1H
startDelayISO 8601 periodThe period to wait before the supervisor starts managing tasks.NoPT5S
periodISO 8601 periodDetermines how often the supervisor executes its management logic. Note that the supervisor also runs in response to certain events, such as tasks succeeding, failing, and reaching their task duration, so this value specifies the maximum time between iterations.NoPT30S
useEarliestSequenceNumberBooleanIf a supervisor is managing a datasource for the first time, it obtains a set of starting sequence numbers from Kinesis. This flag determines whether a supervisor retrieves the earliest or latest sequence numbers in Kinesis. Under normal circumstances, subsequent tasks start from where the previous segments ended so this flag is only used on the first run.Nofalse
completionTimeoutISO 8601 periodThe length of time to wait before Druid declares a publishing task has failed and terminates it. If this is set too low, your tasks may never publish. The publishing clock for a task begins roughly after taskDuration elapses.NoPT6H
lateMessageRejectionPeriodISO 8601 periodConfigure tasks to reject messages with timestamps earlier than this period before the task is created. For example, if lateMessageRejectionPeriod is set to PT1H and the supervisor creates a task at 2016-01-01T12:00Z, messages with timestamps earlier than 2016-01-01T11:00Z are dropped. This may help prevent concurrency issues if your data stream has late messages and you have multiple pipelines that need to operate on the same segments, such as a streaming and a nightly batch ingestion pipeline.No
earlyMessageRejectionPeriodISO 8601 periodConfigure tasks to reject messages with timestamps later than this period after the task reached its taskDuration. For example, if earlyMessageRejectionPeriod is set to PT1H, the taskDuration is set to PT1H and the supervisor creates a task at 2016-01-01T12:00Z. Messages with timestamps later than 2016-01-01T14:00Z are dropped. Note: Tasks sometimes run past their task duration, for example, in cases of supervisor failover. Setting earlyMessageRejectionPeriod too low may cause messages to be dropped unexpectedly whenever a task runs past its originally configured task duration.No
fetchDelayMillisIntegerTime in milliseconds to wait between subsequent calls to fetch records from Kinesis. See Determine fetch settings.No0
awsAssumedRoleArnStringThe AWS assumed role to use for additional permissions.No
awsExternalIdStringThe AWS external ID to use for additional permissions.No
autoScalerConfigObjectDefines autoscaling behavior for Kinesis ingest tasks. See Task autoscaler properties for more information.Nonull

Task autoscaler properties

The following table outlines the configuration options for autoScalerConfig:

enableTaskAutoScalerEnables the auto scaler. If not specified, Druid disables the auto scaler even when autoScalerConfig is not null.Nofalse
taskCountMaxMaximum number of Kinesis ingestion tasks. Must be greater than or equal to taskCountMin. If greater than {numKinesisShards}, Druid sets the maximum number of reading tasks to {numKinesisShards} and ignores taskCountMax.Yes
taskCountMinMinimum number of Kinesis ingestion tasks. When you enable the auto scaler, Druid ignores the value of taskCount in IOConfig and uses taskCountMin for the initial number of tasks to launch.Yes
minTriggerScaleActionFrequencyMillisMinimum time interval between two scale actions.No600000
autoScalerStrategyThe algorithm of autoScaler. Druid only supports the lagBased strategy. See Lag based autoscaler strategy related properties for more information.NoDefaults to lagBased.

Unlike the Kafka indexing service, Kinesis reports lag metrics measured in time difference in milliseconds between the current sequence number and latest sequence number, rather than message count.

The following table outlines the configuration options for autoScalerStrategy:

lagCollectionIntervalMillisThe time period during which Druid collects lag metric points.No30000
lagCollectionRangeMillisThe total time window of lag collection. Use with lagCollectionIntervalMillis to specify the intervals at which to collect lag metric points.No600000
scaleOutThresholdThe threshold of scale out action.No6000000
triggerScaleOutFractionThresholdEnables scale out action if triggerScaleOutFractionThreshold percent of lag points is higher than scaleOutThreshold.No0.3
scaleInThresholdThe threshold of scale in action.No1000000
triggerScaleInFractionThresholdEnables scale in action if triggerScaleInFractionThreshold percent of lag points is lower than scaleOutThreshold.No0.9
scaleActionStartDelayMillisThe number of milliseconds to delay after the supervisor starts before the first scale logic check.No300000
scaleActionPeriodMillisThe frequency in milliseconds to check if a scale action is triggered.No60000
scaleInStepThe number of tasks to reduce at once when scaling down.No1
scaleOutStepThe number of tasks to add at once when scaling out.No2

The following example shows a supervisor spec with lagBased auto scaler enabled.

Click to view the example
"type": "kinesis",
"dataSchema": {
"dataSource": "metrics-kinesis",
"timestampSpec": {
"column": "timestamp",
"format": "auto"
"dimensionsSpec": {
"dimensions": [],
"dimensionExclusions": [
"metricsSpec": [
"name": "count",
"type": "count"
"name": "value_sum",
"fieldName": "value",
"type": "doubleSum"
"name": "value_min",
"fieldName": "value",
"type": "doubleMin"
"name": "value_max",
"fieldName": "value",
"type": "doubleMax"
"granularitySpec": {
"type": "uniform",
"segmentGranularity": "HOUR",
"queryGranularity": "NONE"
"ioConfig": {
"stream": "metrics",
"autoScalerConfig": {
"enableTaskAutoScaler": true,
"taskCountMax": 6,
"taskCountMin": 2,
"minTriggerScaleActionFrequencyMillis": 600000,
"autoScalerStrategy": "lagBased",
"lagCollectionIntervalMillis": 30000,
"lagCollectionRangeMillis": 600000,
"scaleOutThreshold": 600000,
"triggerScaleOutFractionThreshold": 0.3,
"scaleInThreshold": 100000,
"triggerScaleInFractionThreshold": 0.9,
"scaleActionStartDelayMillis": 300000,
"scaleActionPeriodMillis": 60000,
"scaleInStep": 1,
"scaleOutStep": 2
"inputFormat": {
"type": "json"
"endpoint": "",
"taskCount": 1,
"replicas": 1,
"taskDuration": "PT1H"
"tuningConfig": {
"type": "kinesis",
"maxRowsPerSegment": 5000000

Specify data format

The Kinesis indexing service supports both inputFormat and parser to specify the data format. Use the inputFormat to specify the data format for the Kinesis indexing service unless you need a format only supported by the legacy parser.

Supported values for inputFormat include:

  • csv
  • delimited
  • json
  • avro_stream
  • avro_ocf
  • protobuf

For more information, see Data formats. You can also read thrift formats using parser.

Supervisor tuning configuration

The tuningConfig object is optional. If you don't specify the tuningConfig object, Druid uses the default configuration settings.

The following table outlines the configuration options for tuningConfig:

typeStringThe indexing task type. This should always be kinesis.Yes
maxRowsInMemoryIntegerThe number of rows to aggregate before persisting. This number represents the post-aggregation rows. It is not equivalent to the number of input events, but the resulting number of aggregated rows. Druid uses maxRowsInMemory to manage the required JVM heap size. The maximum heap memory usage for indexing scales is maxRowsInMemory * (2 + maxPendingPersists).No100000
maxBytesInMemoryLongThe number of bytes to aggregate in heap memory before persisting. This is based on a rough estimate of memory usage and not actual usage. Normally, this is computed internally. The maximum heap memory usage for indexing is maxBytesInMemory * (2 + maxPendingPersists).NoOne-sixth of max JVM memory
skipBytesInMemoryOverheadCheckBooleanThe calculation of maxBytesInMemory takes into account overhead objects created during ingestion and each intermediate persist. To exclude the bytes of these overhead objects from the maxBytesInMemory check, set skipBytesInMemoryOverheadCheck to true.Nofalse
maxRowsPerSegmentIntegerThe number of rows to aggregate into a segment; this number represents the post-aggregation rows. Handoff occurs when maxRowsPerSegment or maxTotalRows is reached or every intermediateHandoffPeriod, whichever happens first.No5000000
maxTotalRowsLongThe number of rows to aggregate across all segments; this number represents the post-aggregation rows. Handoff occurs when maxRowsPerSegment or maxTotalRows is reached or every intermediateHandoffPeriod, whichever happens first.Nounlimited
intermediateHandoffPeriodISO 8601 periodThe period that determines how often tasks hand off segments. Handoff occurs if maxRowsPerSegment or maxTotalRows is reached or every intermediateHandoffPeriod, whichever happens first.NoP2147483647D
intermediatePersistPeriodISO 8601 periodThe period that determines the rate at which intermediate persists occur.NoPT10M
maxPendingPersistsIntegerMaximum number of persists that can be pending but not started. If a new intermediate persist exceeds this limit, Druid blocks ingestion until the currently running persist finishes. One persist can be running concurrently with ingestion, and none can be queued up. The maximum heap memory usage for indexing scales is maxRowsInMemory * (2 + maxPendingPersists).No0
indexSpecObjectDefines how Druid indexes the data. See IndexSpec for more information.No
indexSpecForIntermediatePersistsObjectDefines segment storage format options to use at indexing time for intermediate persisted temporary segments. You can use indexSpecForIntermediatePersists to disable dimension/metric compression on intermediate segments to reduce memory required for final merging. However, disabling compression on intermediate segments might increase page cache use while they are used before getting merged into final segment published. See IndexSpec for possible values.NoSame as indexSpec
reportParseExceptionsBooleanIf true, Druid throws exceptions encountered during parsing causing ingestion to halt. If false, Druid skips unparseable rows and fields.Nofalse
handoffConditionTimeoutLongNumber of milliseconds to wait for segment handoff. Set to a value >= 0, where 0 means to wait indefinitely.No0
resetOffsetAutomaticallyBooleanControls behavior when Druid needs to read Kinesis messages that are no longer available.
If false, the exception bubbles up causing tasks to fail and ingestion to halt. If this occurs, manual intervention is required to correct the situation, potentially using the Reset Supervisor API. This mode is useful for production, since it highlights issues with ingestion.
If true, Druid automatically resets to the earliest or latest sequence number available in Kinesis, based on the value of the useEarliestSequenceNumber property (earliest if true, latest if false). Note that this can lead to dropping data (if useEarliestSequenceNumber is false) or duplicating data (if useEarliestSequenceNumber is true) without your knowledge. Druid logs messages indicating that a reset has occurred without interrupting ingestion. This mode is useful for non-production situations since it enables Druid to recover from problems automatically, even if they lead to quiet dropping or duplicating of data.
skipSequenceNumberAvailabilityCheckBooleanWhether to enable checking if the current sequence number is still available in a particular Kinesis shard. If false, the indexing task attempts to reset the current sequence number, depending on the value of resetOffsetAutomatically.Nofalse
workerThreadsIntegerThe number of threads that the supervisor uses to handle requests/responses for worker tasks, along with any other internal asynchronous operation.Nomin(10, taskCount)
chatRetriesIntegerThe number of times Druid retries HTTP requests to indexing tasks before considering tasks unresponsive.No8
httpTimeoutISO 8601 periodThe period of time to wait for a HTTP response from an indexing task.NoPT10S
shutdownTimeoutISO 8601 periodThe period of time to wait for the supervisor to attempt a graceful shutdown of tasks before exiting.NoPT80S
recordBufferSizeBytesIntegerThe size of the buffer (heap memory bytes) Druid uses between the Kinesis fetch threads and the main ingestion thread.NoSee Determine fetch settings for defaults.
recordBufferOfferTimeoutIntegerThe number of milliseconds to wait for space to become available in the buffer before timing out.No5000
recordBufferFullWaitIntegerThe number of milliseconds to wait for the buffer to drain before Druid attempts to fetch records from Kinesis again.No5000
fetchThreadsIntegerThe size of the pool of threads fetching data from Kinesis. There is no benefit in having more threads than Kinesis shards.Noprocs * 2, where procs is the number of processors available to the task.
segmentWriteOutMediumFactoryObjectThe segment write-out medium to use when creating segments See Additional Peon configuration: SegmentWriteOutMediumFactory for explanation and available options.NoIf not specified, Druid uses the value from druid.peon.defaultSegmentWriteOutMediumFactory.type.
logParseExceptionsBooleanIf true, Druid logs an error message when a parsing exception occurs, containing information about the row where the error occurred.Nofalse
maxParseExceptionsIntegerThe maximum number of parse exceptions that can occur before the task halts ingestion and fails. Overridden if reportParseExceptions is set.Nounlimited
maxSavedParseExceptionsIntegerWhen a parse exception occurs, Druid keeps track of the most recent parse exceptions. maxSavedParseExceptions limits the number of saved exception instances. These saved exceptions are available after the task finishes in the task completion report. Overridden if reportParseExceptions is set.No0
maxBytesPerPollIntegerThe maximum number of bytes to be fetched from buffer per poll. At least one record is polled from the buffer regardless of this config.No1000000 bytes
repartitionTransitionDurationISO 8601 periodWhen shards are split or merged, the supervisor recomputes shard to task group mappings. The supervisor also signals any running tasks created under the old mappings to stop early at current time + repartitionTransitionDuration. Stopping the tasks early allows Druid to begin reading from the new shards more quickly. The repartition transition wait time controlled by this property gives the stream additional time to write records to the new shards after the split or merge, which helps avoid issues with empty shard handling.NoPT2M
offsetFetchPeriodISO 8601 periodDetermines how often the supervisor queries Kinesis and the indexing tasks to fetch current offsets and calculate lag. If the user-specified value is below the minimum value of PT5S, the supervisor ignores the value and uses the minimum value instead.NoPT30S
useListShardsBooleanIndicates if listShards API of AWS Kinesis SDK can be used to prevent LimitExceededException during ingestion. You must set the necessary IAM permissions.Nofalse


The following table outlines the configuration options for indexSpec:

bitmapObjectCompression format for bitmap indexes. Druid supports roaring and concise bitmap types.NoRoaring
dimensionCompressionStringCompression format for dimension columns. Choose from LZ4, LZF, or uncompressed.NoLZ4
metricCompressionStringCompression format for primitive type metric columns. Choose from LZ4, LZF, uncompressed, or none.NoLZ4
longEncodingStringEncoding format for metric and dimension columns with type long. Choose from auto or longs. auto encodes the values using sequence number or lookup table depending on column cardinality and stores them with variable sizes. longs stores the value as is with 8 bytes each.Nolongs


This section describes how to use the Supervisor API with the Kinesis indexing service.

AWS authentication

Druid uses AWS access and secret keys to authenticate Kinesis API requests. There are a few ways to provide this information to Druid:

  1. Using roles or short-term credentials:

    Druid looks for credentials set in environment variables, via Web Identity Token, in the default profile configuration file, and from the EC2 instance profile provider (in this order).

  2. Using long-term security credentials:

    You can directly provide your AWS access key and AWS secret key in the file as shown in the example below:


Note: AWS does not recommend providing long-term security credentials in configuration files since it might pose a security risk. If you use this approach, it takes precedence over all other methods of providing credentials.

To ingest data from Kinesis, ensure that the policy attached to your IAM role contains the necessary permissions. The required permissions depend on the value of useListShards.

If the useListShards flag is set to true, you need following permissions:

  • ListStreams to list your data streams.
  • Get* required for GetShardIterator.
  • GetRecords to get data records from a data stream's shard.
  • ListShards to get the shards for a stream of interest.

The following is an example policy:

"Effect": "Allow",
"Action": ["kinesis:List*"],
"Resource": ["*"]
"Effect": "Allow",
"Action": ["kinesis:Get*"],
"Resource": [<ARN for shards to be ingested>]

If the useListShards flag is set to false, you need following permissions:

  • ListStreams to list your data streams.
  • Get* required for GetShardIterator.
  • GetRecords to get data records from a data stream's shard.
  • DescribeStream to describe the specified data stream.

The following is an example policy:

"Effect": "Allow",
"Action": ["kinesis:ListStreams"],
"Resource": ["*"]
"Effect": "Allow",
"Action": ["kinesis:DescribeStream"],
"Resource": ["*"]
"Effect": "Allow",
"Action": ["kinesis:Get*"],
"Resource": [<ARN for shards to be ingested>]

Get supervisor status report

To retrieve the current status report for a single supervisor, send a GET request to the /druid/indexer/v1/supervisor/:supervisorId/status endpoint.

The report contains the state of the supervisor tasks, the latest sequence numbers, and an array of recently thrown exceptions reported as recentErrors. You can control the maximum size of the exceptions using the druid.supervisor.maxStoredExceptionEvents configuration.

The two properties related to the supervisor's state are state and detailedState. The state property contains a small number of generic states that apply to any type of supervisor, while the detailedState property contains a more descriptive, implementation-specific state that may provide more insight into the supervisor's activities.


The following table lists detailedState values and their corresponding state mapping:

Detailed stateCorresponding stateDescription
UNHEALTHY_SUPERVISORUNHEALTHY_SUPERVISORThe supervisor encountered errors on previous druid.supervisor.unhealthinessThreshold iterations.
UNHEALTHY_TASKSUNHEALTHY_TASKSThe last druid.supervisor.taskUnhealthinessThreshold tasks all failed.
UNABLE_TO_CONNECT_TO_STREAMUNHEALTHY_SUPERVISORThe supervisor is encountering connectivity issues with Kinesis and has not successfully connected in the past.
LOST_CONTACT_WITH_STREAMUNHEALTHY_SUPERVISORThe supervisor is encountering connectivity issues with Kinesis but has successfully connected in the past.
PENDING (first iteration only)PENDINGThe supervisor has been initialized but hasn't started connecting to the stream.
CONNECTING_TO_STREAM (first iteration only)RUNNINGThe supervisor is trying to connect to the stream and update partition data.
DISCOVERING_INITIAL_TASKS (first iteration only)RUNNINGThe supervisor is discovering already-running tasks.
CREATING_TASKS (first iteration only)RUNNINGThe supervisor is creating tasks and discovering state.
RUNNINGRUNNINGThe supervisor has started tasks and is waiting for taskDuration to elapse.
SUSPENDEDSUSPENDEDThe supervisor is suspended.
STOPPINGSTOPPINGThe supervisor is stopping.

On each iteration of the supervisor's run loop, the supervisor completes the following tasks in sequence:

  1. Fetch the list of shards from Kinesis and determine the starting sequence number for each shard (either based on the last processed sequence number if continuing, or starting from the beginning or ending of the stream if this is a new stream).
  2. Discover any running indexing tasks that are writing to the supervisor's datasource and adopt them if they match the supervisor's configuration, else signal them to stop.
  3. Send a status request to each supervised task to update the view of the state of the tasks under supervision.
  4. Handle tasks that have exceeded taskDuration and should transition from the reading to publishing state.
  5. Handle tasks that have finished publishing and signal redundant replica tasks to stop.
  6. Handle tasks that have failed and clean up the supervisor's internal state.
  7. Compare the list of healthy tasks to the requested taskCount and replicas configurations and create additional tasks if required.

The detailedState property shows additional values (marked with "first iteration only" in the preceding table) the first time the supervisor executes this run loop after startup or after resuming from a suspension. This is intended to surface initialization-type issues, where the supervisor is unable to reach a stable state. For example, if the supervisor cannot connect to Kinesis, if it's unable to read from the stream, or cannot communicate with existing tasks. Once the supervisor is stable; that is, once it has completed a full execution without encountering any issues, detailedState will show a RUNNING state until it is stopped, suspended, or hits a failure threshold and transitions to an unhealthy state.

Update existing supervisors

To update an existing supervisor spec, send a POST request to the /druid/indexer/v1/supervisor endpoint.

When you call this endpoint on an existing supervisor for the same datasource, the running supervisor signals its tasks to stop reading and begin publishing their segments, exiting itself. Druid then uses the provided configuration from the request body to create a new supervisor with a new set of tasks that start reading from the sequence numbers, where the previous now-publishing tasks left off, but using the updated schema. In this way, configuration changes can be applied without requiring any pause in ingestion.

You can achieve seamless schema migrations by submitting the new schema using the /druid/indexer/v1/supervisor endpoint.

Suspend and resume a supervisor

To suspend a supervisor, send a POST request to the /druid/indexer/v1/supervisor/:supervisorId/suspend endpoint. Suspending a supervisor does not prevent it from operating and emitting logs and metrics. It ensures that no indexing tasks are running until the supervisor resumes.

To resume a supervisor, send a POST request to the /druid/indexer/v1/supervisor/:supervisorId/resume endpoint.

Reset a supervisor

The supervisor must be running for this endpoint to be available

To reset a supervisor, send a POST request to the /druid/indexer/v1/supervisor/:supervisorId/reset endpoint. This endpoint clears stored sequence numbers, prompting the supervisor to start reading from either the earliest or the latest sequence numbers in Kinesis (depending on the value of useEarliestSequenceNumber). After clearing stored sequence numbers, the supervisor kills and recreates active tasks, so that tasks begin reading from valid sequence numbers.

This endpoint is useful when you need to recover from a stopped state due to missing sequence numbers in Kinesis. Use this endpoint with caution as it may result in skipped messages, leading to data loss or duplicate data.

The indexing service keeps track of the latest persisted sequence number to provide exactly-once ingestion guarantees across tasks. Subsequent tasks must start reading from where the previous task completed for the generated segments to be accepted. If the messages at the expected starting sequence numbers are no longer available in Kinesis (typically because the message retention period has elapsed or the topic was removed and re-created) the supervisor will refuse to start and in-flight tasks will fail. This endpoint enables you to recover from this condition.

Resetting Offsets for a supervisor

To reset partition offsets for a supervisor, send a POST request to the /druid/indexer/v1/supervisor/:supervisorId/resetOffsets endpoint. This endpoint clears stored sequence numbers, prompting the supervisor to start reading from the specified offsets. After resetting stored offsets, the supervisor kills and recreates any active tasks pertaining to the specified partitions, so that tasks begin reading specified offsets. For partitions that are not specified in this operation, the supervisor will resume from the last stored offset.

Use this endpoint with caution as it may result in skipped messages, leading to data loss or duplicate data.

Terminate a supervisor

To terminate a supervisor and its associated indexing tasks, send a POST request to the /druid/indexer/v1/supervisor/:supervisorId/terminate endpoint. This places a tombstone marker in the database to prevent the supervisor from being reloaded on a restart and then gracefully shuts down the currently running supervisor. The tasks stop reading and begin publishing their segments immediately. The call returns after all tasks have been signaled to stop but before the tasks finish publishing their segments.

The terminated supervisor continues exists in the metadata store and its history can be retrieved. The only way to restart a terminated supervisor is by submitting a functioning supervisor spec to /druid/indexer/v1/supervisor.

Capacity planning

Kinesis indexing tasks run on Middle Managers and are limited by the resources available in the Middle Manager cluster. In particular, you should make sure that you have sufficient worker capacity, configured using the druid.worker.capacity property, to handle the configuration in the supervisor spec. Note that worker capacity is shared across all types of indexing tasks, so you should plan your worker capacity to handle your total indexing load, such as batch processing, streaming tasks, and merging tasks. If your workers run out of capacity, Kinesis indexing tasks queue and wait for the next available worker. This may cause queries to return partial results but will not result in data loss, assuming the tasks run before Kinesis purges those sequence numbers.

A running task can be in one of two states: reading or publishing. A task remains in reading state for the period defined in taskDuration, at which point it transitions to publishing state. A task remains in publishing state for as long as it takes to generate segments, push segments to deep storage, and have them loaded and served by a Historical process or until completionTimeout elapses.

The number of reading tasks is controlled by replicas and taskCount. In general, there are replicas * taskCount reading tasks. An exception occurs if taskCount > {numKinesisShards}, in which case Druid uses {numKinesisShards} tasks. When taskDuration elapses, these tasks transition to publishing state and replicas * taskCount new reading tasks are created. To allow for reading tasks and publishing tasks to run concurrently, there should be a minimum capacity of:

workerCapacity = 2 * replicas * taskCount

This value is for the ideal situation in which there is at most one set of tasks publishing while another set is reading. In some circumstances, it is possible to have multiple sets of tasks publishing simultaneously. This would happen if the time-to-publish (generate segment, push to deep storage, load on Historical) is greater than taskDuration. This is a valid and correct scenario but requires additional worker capacity to support. In general, it is a good idea to have taskDuration be large enough that the previous set of tasks finishes publishing before the current set begins.

Shards and segment handoff

Each Kinesis indexing task writes the events it consumes from Kinesis shards into a single segment for the segment granularity interval until it reaches one of the following limits: maxRowsPerSegment, maxTotalRows, or intermediateHandoffPeriod. At this point, the task creates a new shard for this segment granularity to contain subsequent events.

The Kinesis indexing task also performs incremental hand-offs so that the segments created by the task are not held up until the task duration is over. When the task reaches one of the maxRowsPerSegment, maxTotalRows, or intermediateHandoffPeriod limits, it hands off all the segments and creates a new set of segments for further events. This allows the task to run for longer durations without accumulating old segments locally on Middle Manager processes.

The Kinesis indexing service may still produce some small segments. For example, consider the following scenario:

  • Task duration is 4 hours
  • Segment granularity is set to an HOUR
  • The supervisor was started at 9:10

After 4 hours at 13:10, Druid starts a new set of tasks. The events for the interval 13:00 - 14:00 may be split across existing tasks and the new set of tasks which could result in small segments. To merge them together into new segments of an ideal size (in the range of ~500-700 MB per segment), you can schedule re-indexing tasks, optionally with a different segment granularity.

For more detail, see Segment size optimization.

Determine fetch settings

Kinesis indexing tasks fetch records using fetchThreads threads. If fetchThreads is higher than the number of Kinesis shards, the excess threads are unused. Each fetch thread fetches up to 10 MB of records at once from a Kinesis shard, with a delay between fetches of fetchDelayMillis. The records fetched by each thread are pushed into a shared queue of size recordBufferSizeBytes. The main runner thread for each task polls up to maxRecordsPerPoll records from the queue at once.

The default values for these parameters are:

  • fetchThreads: Twice the number of processors available to the task. The number of processors available to the task is the total number of processors on the server, divided by druid.worker.capacity (the number of task slots on that particular server). This value is further limited so that the total data record data fetched at a given time does not exceed 5% of the max heap configured, assuming that each thread fetches 10 MB of records at once. If the value specified for this configuration is higher than this limit, no failure occurs, but a warning is logged, and the value is implicitly lowered to the max allowed by this constraint.
  • fetchDelayMillis: 0 (no delay between fetches).
  • recordBufferSizeBytes: 100 MB or an estimated 10% of available heap, whichever is smaller.
  • maxBytesPerPoll: 1000000.

Kinesis places the following restrictions on calls to fetch records:

  • Each data record can be up to 1 MB in size.
  • Each shard can support up to 5 transactions per second for reads.
  • Each shard can read up to 2 MB per second.
  • The maximum size of data that GetRecords can return is 10 MB.

If the above limits are exceeded, Kinesis throws ProvisionedThroughputExceededException errors. If this happens, Druid Kinesis tasks pause by fetchDelayMillis or 3 seconds, whichever is larger, and then attempt the call again.

In most cases, the default settings for fetch parameters are sufficient to achieve good performance without excessive memory usage. However, in some cases, you may need to adjust these parameters to control fetch rate and memory usage more finely. Optimal values depend on the average size of a record and the number of consumers you have reading from a given shard, which will be replicas unless you have other consumers also reading from this Kinesis stream.


The Kinesis indexing service supports de-aggregation of multiple rows packed into a single record by the Kinesis Producer Library's aggregate method for more efficient data transfer.


Resharding is an advanced operation that lets you adjust the number of shards in a stream to adapt to changes in the rate of data flowing through a stream.

When changing the shard count for a Kinesis stream, there is a window of time around the resharding operation with early shutdown of Kinesis ingestion tasks and possible task failures.

The early shutdowns and task failures are expected. They occur because the supervisor updates the shard to task group mappings as shards are closed and fully read. This ensures that tasks are not running with an assignment of closed shards that have been fully read and balances distribution of active shards across tasks.

This window with early task shutdowns and possible task failures concludes when:

  • All closed shards have been fully read and the Kinesis ingestion tasks have published the data from those shards, committing the "closed" state to metadata storage.
  • Any remaining tasks that had inactive shards in the assignment have been shut down. These tasks would have been created before the closed shards were completely drained.

Note that when the supervisor is running and detects new partitions, tasks read new partitions from the earliest offsets, irrespective of the useEarliestSequence setting. This is because these new shards were immediately discovered and are therefore unlikely to experience a lag.

If resharding occurs when the supervisor is suspended and useEarliestSequence is set to false, resuming the supervisor causes tasks to read the new shards from the latest sequence. This is by design so that the consumer can catch up quickly with any lag accumulated while the supervisor was suspended.

Kinesis known issues

Before you deploy the Kinesis extension to production, consider the following known issues:

  • Avoid implementing more than one Kinesis supervisor that reads from the same Kinesis stream for ingestion. Kinesis has a per-shard read throughput limit and having multiple supervisors on the same stream can reduce available read throughput for an individual supervisor's tasks. Multiple supervisors ingesting to the same Druid datasource can also cause increased contention for locks on the datasource.
  • The only way to change the stream reset policy is to submit a new ingestion spec and set up a new supervisor.
  • If ingestion tasks get stuck, the supervisor does not automatically recover. You should monitor ingestion tasks and investigate if your ingestion falls behind.
  • A Kinesis supervisor can sometimes compare the checkpoint offset to retention window of the stream to see if it has fallen behind. These checks fetch the earliest sequence number for Kinesis which can result in IteratorAgeMilliseconds becoming very high in AWS CloudWatch.