Pull Kafka records over HTTP

Use pollFromKafka when an HTTP client needs to read a Kafka topic without connecting to the broker. The client asks for one batch at a time and keeps the cursor that says where to resume.

Choose a mode

Mode When to use it

CLIENT_API (default)

An HTTP client calls an API you define. Use restApi for the endpoint, cursorExpression to read the client’s cursor, and map to shape the response. This tutorial uses the OPAQUE cursor format: the client stores the token and sends it back without interpreting it.

RELAY

A typical use is moving records from a lower-security zone into a higher-security zone, such as a utility’s operational technology (OT) network, when the lower-security zone cannot initiate connections to it. The receiving flow in the higher-security zone uses receiveFromRelay to open every connection and fetch records. The serving flow in the lower-security zone uses relayApi and sets mode = RELAY on pollFromKafka. Connect defines the HTTP contract, so leave cursorExpression unset.

Define the endpoint

This example serves an events topic at GET /events. Register the following YAML as an OpenAPIv3 resource named events-pull-api in the same organization as the flow. See Resource Registry.

openapi: 3.0.3
info:
  title: Events pull API
  version: 1.0.0
paths:
  /events:
    get:
      operationId: pullEvents
      parameters:
        - name: cursor
          in: query
          required: false
          schema:
            type: string
      responses:
        '200':
          description: The next batch and the cursor to send after processing it
          content:
            application/json:
              schema:
                type: object
                required: [records, cursor]
                properties:
                  records:
                    type: array
                    items:
                      type: object
                  cursor:
                    type: string
                    minLength: 1

Build and deploy the integration flow

Replace my-org and the broker address with your values. This example uses a Kafka secret named events-kafka. If your broker requires authentication, register the secret in the same organization. Otherwise omit authenticationConfigKey. Use an existing topic with records and a new consumer group. To see records in both example responses, set maxBatchRecords below the number of records in the topic.

import com.greenbird.metercloud.integration.flow.spec.FlowExchangePattern.RequestResponse
import com.greenbird.metercloud.integration.flow.spec.FlowPipelineDeploymentScope.SINGLETON
import com.greenbird.metercloud.integration.flow.spec.dsl.KafkaCursorFormat.OPAQUE
import com.greenbird.metercloud.integration.flow.spec.dsl.KafkaPollMode.CLIENT_API
import com.greenbird.metercloud.integration.flow.spec.dsl.KafkaStartPolicy.EARLIEST
import com.greenbird.metercloud.integration.flow.spec.dsl.flowConfig
import com.greenbird.utilihive.integration.deployment.flow.FlowDeploy

object EventsPullFlow {
    @FlowDeploy
    fun eventsPull() = flowConfig {
        id = "events-pull"
        ownerId = "my-org"
        exchangePattern = RequestResponse
        flowPipelineDeploymentStrategy { scope = SINGLETON }
        maxNumberOfInFlightMessages = 1
        redeliveryStrategy {
            redeliveryMaxNo = 0
            redeliveryMillis = 15_000
        }

        restApi {
            id = "events-api"
            apiSpecId = "OpenAPIv3:events-pull-api:latest"
        }

        pollFromKafka {
            id = "read-events"
            brokerList = "kafka.example.com:9093"
            topic = "events"
            groupId = "events-pull.client-a"
            authenticationConfigKey = "events-kafka"
            mode = CLIENT_API
            cursorFormat = OPAQUE
            cursorExpression = """jsoniq:#input.exchangePropertiesMap."http.query.cursor""""
            startPolicy = EARLIEST
            maxBatchRecords = 100
            maxWaitMillis = 1_000
            kafkaTimeoutMillis = 5_000
        }

        map {
            id = "kafka-pull-response"
            mapSpec = """
                let #cursor := for #property in #input.messageExchangeProperties[]
                    where #property.name = "kafkaNextCursor"
                    return #property.value
                return {
                  "records": #input.payload,
                  "cursor": #cursor
                }
            """.trimIndent()
        }
    }
}

The JSONiq expression in cursorExpression reads the incoming query parameter. In mapSpec, read exchange properties from #input.messageExchangeProperties[]; exchangePropertiesMap is not available there. Return kafkaNextCursor unchanged, including for an empty batch. Expose kafkaHasMore if clients need to know whether to poll again right away. Expose kafkaGaps if they need to know when Kafka retention has removed unread records. Keep response mapping free of side effects: a retry may run it again.

Give each independent client its own integration flow and group. Never reset the group’s Kafka offsets or share the group with another consumer. When the client omits the cursor or sends an empty one, Connect resumes from the group’s committed position. If the group has no position to resume from, Connect uses startPolicy. EARLIEST reads records still in the topic; LATEST starts after the records already there.

Deploy the flow with the SDK Deployer and grant the client Flow Access.

Validate the flow and set its limits

Use exchangePattern = RequestResponse and flowPipelineDeploymentStrategy { scope = SINGLETON }. Add at most one pollFromKafka, without a processingStrategy. Set maxNumberOfInFlightMessages = 1 to process one pull request at a time. See Throttling for sizing the buffer and stash.

Disable redelivery with redeliveryStrategy { redeliveryMaxNo = 0 }. The HTTP source still uses redeliveryMillis to set the deadline for the single attempt. Keep redeliveryMillis higher than maxWaitMillis plus kafkaTimeoutMillis plus 1000 ms. In this example, 15000 ms is greater than 7000 ms. This gives the processor time to return a Kafka timeout before the HTTP source gives up on the request. If another flow calls a Headless flow that contains pollFromKafka, set SINGLETON on the Headless flow and configure redeliveryStrategy on the calling flow.

Set maxBatchRecords between 1 and 1000. maxBatchBytes must not exceed the flow-server’s mc.flow-server.max-batch-bytes-limit (16 MiB by default). If it does, the pipeline fails to load, even if the flow spec was accepted.

Use the cursor

Send one request at a time. Finish processing the batch before sending its cursor back. Sending the cursor tells Connect that you processed all records before it. Connect preserves order within a partition, not across partitions.

Run both examples in the same fresh Bash session. For an OIDC Flow Access route, set EVENTS_URL to the route’s URL for /events and ACCESS_TOKEN to the client’s access token. The default endpoint path is /{ownerId}/rs/events-pull/events. Use curl and jq to fetch and inspect the first batch without a cursor:

pull_batch() {
  : "${EVENTS_URL:?Set EVENTS_URL}" "${ACCESS_TOKEN:?Set ACCESS_TOKEN}"
  local body
  if ! body=$(curl --fail-with-body --silent --show-error \
    -H "Authorization: Bearer $ACCESS_TOKEN" "$@" "$EVENTS_URL"); then
    [[ -z "$body" ]] || printf '%s\n' "$body" >&2
    return 1
  fi
  if ! jq -es 'length == 1 and (.[0] | objects |
    (.records | type == "array") and (.cursor | strings | length > 0))' \
    > /dev/null <<< "$body"; then
    printf '%s\n' 'Expected a records array and a nonempty cursor.' >&2
    return 1
  fi
  printf '%s\n' "$body"
}

first_batch=$(pull_batch) &&
  batch=$first_batch &&
  printf '%s\n' "$batch" | jq '.records'

If the first request fails, retry it before continuing. Run the next example only after the first request succeeds and you have processed its records. Use the returned cursor to request the next batch:

if cursor=$(jq -er '.cursor | strings | select(length > 0)' <<< "${batch:-null}"); then
  next_batch=$(pull_batch --get --data-urlencode "cursor=$cursor") &&
    batch=$next_batch &&
    printf '%s\n' "$batch" | jq '.records'
else
  printf '%s\n' 'Fetch and process the first batch before sending its cursor.' >&2
  false
fi

For later requests, repeat the second example after processing each batch. If you did not see the output from a successful request, inspect the saved records with jq '.records' <<< "$batch" and process them before sending the new cursor. If you did not receive a response, retry with the cursor you sent in that request, or omit it again if the request had none. A failed request leaves batch unchanged. A retry starts at the same positions, subject to Kafka retention, but a capped batch can contain a different mix of records from each partition.

HTTP status Meaning Client action

400

The cursor is invalid or can no longer be served.

Rerun the first example, which sends no cursor, to resume from the group’s committed position. Be prepared to process records again.

503

The Kafka reader is busy.

Retry with the same cursor.

504

Kafka was unavailable or did not answer in time.

Retry with the same cursor.

500

A server error occurred, such as a Kafka authentication or commit failure.

Retry with the same cursor. If the error persists, ask an operator to investigate.

After a pipeline restart or move to another node, a successful read with an older cursor can cause a newer cursor to be rejected. If you get 400, omit the cursor. Do not edit the cursor or reset the Kafka group.