Send logs to the Logit.io HTTPS /v2 endpoint as a JSON array or newline-delimited JSON (NDJSON), with 1 to 1,000 events and a body of at most 9,800,000 bytes per request. On HTTP 413, split the batch or drop and log a rejected singleton. On HTTP 503, honour Retry-After: 5 and retry with bounded backoff, then check OpenSearch Dashboards for the events that the API reported as queued.
Contents
Send two logs in one request
Start with a batch you can recognise in Discover. A worker that writes a start and finish event is enough to check that the endpoint accepts the file, separates the records and leaves the fields you need for a search. Use synthetic messages so you can share your results with the team.
- Choose the destination. Sign in to Logit.io, select the Logs stack you want to send to and open the HTTPS log integration guide. Use its integration setup to get the endpoint and that stack's API key. Put the full HTTPS URL ending in
/v2inLOGIT_HTTPS_URLand provide the key to your shell or job asLOGIT_API_KEY. The values shown in the example are placeholders. - Send the key in one header. Use
ApiKeyand keep the key out of your command history, source files and URLs. The API checksApiKeyfirst, thenApi-Key, thenAuthorizationwith the Splunk or HTTP Basic scheme. With Basic, the key is the password. If the selected header supplies no key, it falls back to?token=. Bearer authentication is unsupported. When updating a sender, remove stale credential headers so they cannot take precedence over the intended key. - Send the file as bytes. The example uses curl in Bash and writes two UTF-8 JSON objects on separate lines. Use
--data-binaryto preserve those line breaks. Change the demo IDs when you want to distinguish a new run from earlier ones.
cat > events.ndjson <<'NDJSON'
{"batch_id":"https-demo-01","log_event_id":"https-demo-01-a","message":"Worker started","level":"info"}
{"batch_id":"https-demo-01","log_event_id":"https-demo-01-b","message":"Worker finished","level":"info"}
NDJSON
curl --disable -i --proto '=https' --connect-timeout 3 --max-time 10 \
"${LOGIT_HTTPS_URL:-https://your-endpoint.example/v2}" \
-H "ApiKey: ${LOGIT_API_KEY:-YOUR_API_KEY}" \
-H "Content-Type: application/x-ndjson" \
--data-binary @events.ndjson
An illustrative response is HTTP 202 Accepted with a JSON message of Message Received, Thanks. Both events are queued for processing. Give them time to appear in OpenSearch and use the checks below to confirm what was indexed. Keep the two event IDs handy, especially if you try the Python sender against the same file. A successful second send can produce a second copy of each event.
The JSON array form takes application/json and wraps the objects in square brackets. NDJSON takes application/x-ndjson, application/ndjson or application/jsonl and uses one object per line. Blank lines are ignored. Both formats give you separate logs for the members of the batch. For a file that already has one event per line, NDJSON lets the sender work through it without first loading and converting a whole array.
Leave LogType unset for this example. It defaults to general, which parses the JSON fields into the document root. If your stack uses a Logstash filter branch selected by type, choose the appropriate LogType for the request and batch those events together. One value applies to every event in the request. If you previously added a split filter and a LogType: json_array header specifically for array uploads, you can remove them when moving that sender to native batching.
Measure the bytes you actually send
A count cap works for short status messages until a stack trace or an escaped payload makes a batch much larger. Keep two budgets as you build the body. Flush at 1,000 events or when adding the next complete event would exceed your byte budget, whichever comes first. Measure the bytes of the UTF-8 body after encoding, including the line terminator for every NDJSON event. If you use a JSON array, include the brackets and commas too. A character count can undercount the body when it contains accented text or other multibyte characters. The size of a compacted object can also differ from the length of the original line.
The client below uses 9,700,000 bytes as its batching target, leaving 100,000 bytes below the documented 9,800,000-byte body limit. The smaller target determines which events are grouped together. The client still sends a single event on its own if its encoded line is within the published limit. The API checks the raw request body against the 9,800,000-byte limit on arrival. Even a body within that limit can get 413 if one event's processing record exceeds the same limit once serialised. Splitting the request can save its neighbours. Split only between complete events so both halves remain valid NDJSON.
For a periodic file export, you can flush when you reach either cap and again at end of file. For a live sender, also set a maximum waiting time so a quiet worker ships its last few events promptly. Smaller batches use more requests, but they reduce the records you have to replay after an uncertain response. Set the normal batch size from the delay your team can tolerate and the volume it needs to send. Leave room to investigate unusually large records without tying up every sender.
Keep split and retry paths separate
Use Python 3 with requests. Save the program as batch_logs.py and use the same environment variables as the curl example. The program reads the input as a stream of lines, validates each non-empty line as a JSON object, counts the original UTF-8 line bytes it will send and reuses a session. It sends each child batch in order after a 413. It sends a singleton within the published 9,800,000-byte limit on its own. It logs the input line number and skips any line over that limit, allowing the remaining lines to continue. For a sender that must retain those events, route the original record to storage you operate for inspection and replay. Keep the log message to metadata such as the input offset and byte count so a huge or sensitive event stays out of the sender's own logs.
import argparse
import json
import logging
import math
import os
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import requests
MAX_EVENTS = 1_000
MAX_BYTES = 9_700_000
LIMIT_BYTES = 9_800_000
ATTEMPTS = 5
MAX_WAIT = 60
def reject_non_json_constant(value):
raise ValueError(f"Invalid JSON constant: {value}")
def parse_finite_float(value):
number = float(value)
if not math.isfinite(number):
raise ValueError("Non-finite JSON number")
return number
def batches(lines):
batch, size = [], 0
for line_number, line in enumerate(lines, 1):
if not line.strip():
continue
event = json.loads(
line,
parse_float=parse_finite_float,
parse_constant=reject_non_json_constant,
)
if not isinstance(event, dict):
raise ValueError(f"Expected a JSON object on line {line_number}")
encoded = line.rstrip("\r\n").encode("utf-8") + b"\n"
if len(encoded) > MAX_BYTES:
# Flush pending events before handing off the oversized line.
if batch:
yield batch
batch, size = [], 0
yield [(line_number, encoded)]
continue
if len(batch) == MAX_EVENTS or size + len(encoded) > MAX_BYTES:
yield batch
batch, size = [], 0
batch.append((line_number, encoded))
size += len(encoded)
if batch:
yield batch
def retry_after_seconds(value):
if not value:
return 0
value = value.strip()
try:
if value.isascii() and value.isdecimal():
delay = int(value.lstrip("0") or "0")
else:
date = parsedate_to_datetime(value)
if date.tzinfo is None:
date = date.replace(tzinfo=timezone.utc)
delay = max(0, (date - datetime.now(timezone.utc)).total_seconds())
except (ValueError, TypeError, OverflowError):
return 0
if delay > MAX_WAIT:
raise RuntimeError(f"Retry-After exceeds {MAX_WAIT} seconds")
return delay
def send_batch(session, url, batch):
if len(batch) == 1 and len(batch[0][1]) > LIMIT_BYTES:
logging.error("Skipping line %d: exceeds published byte limit", batch[0][0])
return 0
body = b"".join(encoded for _, encoded in batch)
for attempt in range(ATTEMPTS):
delay = 0
try:
response = session.post(
url, data=body, timeout=(3, 10), allow_redirects=False
)
except requests.exceptions.SSLError:
raise RuntimeError("TLS verification failed") from None
except (requests.ConnectionError, requests.Timeout):
outcome = "connection error or timeout"
else:
status = response.status_code
outcome = f"HTTP {status}"
if status == 202:
return len(batch)
if status == 413:
if len(batch) == 1:
logging.error("Dropping line %d: HTTP 413", batch[0][0])
return 0
middle = len(batch) // 2
left = send_batch(session, url, batch[:middle])
return left + send_batch(session, url, batch[middle:])
if status != 429 and not 500 <= status < 600:
raise RuntimeError(outcome)
delay = retry_after_seconds(response.headers.get("Retry-After"))
if attempt == ATTEMPTS - 1:
raise RuntimeError(f"{outcome} after {ATTEMPTS} attempts")
jitter = random.uniform(0, min(30, 2 ** attempt))
time.sleep(max(delay, jitter))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("ndjson_file")
args = parser.parse_args()
url = os.environ["LOGIT_HTTPS_URL"]
if not url.startswith("https://"):
raise SystemExit("LOGIT_HTTPS_URL must start with https://")
queued, dropped = 0, 0
try:
with requests.Session() as session, open(
args.ndjson_file, encoding="utf-8"
) as lines:
session.headers.update({
"ApiKey": os.environ["LOGIT_API_KEY"],
"Content-Type": "application/x-ndjson",
})
for batch in batches(lines):
accepted = send_batch(session, url, batch)
queued += accepted
dropped += len(batch) - accepted
except (ValueError, RuntimeError) as error:
raise SystemExit(str(error)) from None
print(f"Queued: {queued}; dropped: {dropped}")
return 2 if dropped else 0
if __name__ == "__main__":
raise SystemExit(main())
Run it with the demonstration file from the first step. For the dashboard check, use one sender or change the batch and event IDs before running the second.
python3 batch_logs.py events.ndjson
For the two sample events, an illustrative summary is Queued: 2; dropped: 0. The program exits with status 2 if it completes after skipping a line that exceeded the published limit or after the server rejected a singleton with HTTP 413. It stops on a terminal HTTP response or exhausted retries. It has no durable checkpoint. If the run stops partway through a file, earlier requests or earlier split batches may already have reached the API. Start from a known checkpoint in an operational sender, or replay with the same event IDs and a plan to handle duplicates.
Each request uses a 3-second connect timeout and a 10-second read timeout. The sender retries connection errors, timeouts, 429 and server errors. It waits for the greater of the server's Retry-After value and a random delay in an exponentially growing window. The backoff component is capped. If the server asks for more than 60 seconds, the sender gives up on that batch and exits with an error. The five attempts include the first send. Keep concurrency bounded across senders too. If every worker gets the same retry delay, every worker may wake up together. Start with a small number of concurrent sends and track how often they finish in one attempt before raising concurrency.
Read the response before resending
Record the response status with the number of events, encoded bytes and attempt number. Those three values help you tell whether the fix belongs in batching, request validation or the retry loop. This table uses illustrative response values in the form documented by the HTTPS integration guide.
| HTTP | What to do | Example response |
|---|---|---|
202 | Record the acceptance and look for the events in OpenSearch Dashboards. | Message Received, Thanks |
400 | Repair the body or the event before another attempt. | {"message":"Invalid request body"} |
401 | Check the stack key and how the sender supplies it. The key is a UUIDv4. | Missing credentials or an invalid key format |
403 | Stop the sender for an inactive stack or update it to an active stack key. | code is stack_disabled |
413 | Split the input into requests of at most 1,000 events. | Too many events |
413 | Reduce body bytes. If a single event is rejected, log and skip it or retain it separately. | The data value transmitted exceeds the capacity limit. |
415 | Set a supported Content-Type that matches the body. | You didn't send application/json |
503 | Keep the body and IDs, wait and retry within your attempt limit. | Service temporarily unavailable, retry later with Retry-After: 5 |
429 or other 5xx | Honour the header when present and use bounded backoff with jitter. | Retry-After when present |
If the body is rejected, look for an invalid line, an empty batch, a scalar where an object should be, a non-standard number like NaN or a compressed body. Send plain UTF-8 JSON. One invalid event rejects the entire batch before queueing. Isolate bad lines and fix or remove them. If the response is 415, inspect the actual HTTP header the client sends. Changing the file extension leaves the request media type unchanged. An NDJSON file needs an NDJSON content type even though every line contains valid JSON.
If the key is rejected, check which stack owns it and which credential header the sender is using. 401 points to missing or malformed credentials. A well-formed key with no active stack can get 403 with stack_disabled. A new stack's key can take up to five minutes to be accepted. After confirming the stack is active and ready, try one small request. For a disabled or cancelled stack, remove the drain or stop the shipper instead of leaving it in an automatic retry loop.
If a retry follows a timeout or 503, already queued events can appear again. A connection can fail after queueing, and a 503 can arrive after part of the batch was queued. For example, if the start event was queued and the sender cannot confirm the outcome, a retry can produce two start records and one finish record. Use an ID assigned where the event is created, or a stable source identifier plus a record offset for a file. Reuse that ID on every retry and deduplicate downstream where your workflow requires it. Two lines with the same message can represent different events, so deduplicating by message alone can hide legitimate activity.
Match the queued batch to indexed logs
- Open OpenSearch Dashboards from the same Logs stack and go to Discover. Choose
logstash-*as the index pattern and use@timestampas its time field. Start with a time range that includes the send. If your events carry old timestamps that the pipeline uses, search the window for those timestamps as well. - Set the query language to DQL and search for the start event with both IDs. On default stacks, string fields such as the two demo IDs have
.keywordsubfields for exact-value filters. Use those subfields or the field name shown in your stack's mapping. Addbatch_id,log_event_idandmessageas columns so you can read the match without opening the document.
batch_id.keyword: "https-demo-01" and log_event_id.keyword: "https-demo-01-a"

For a single send of the demo file, expect one start event. Run the batch-only query to see the start and finish together.
batch_id.keyword: "https-demo-01"
Expect two distinct IDs. If you see more than two rows, compare the IDs before concluding that the worker ran twice. Repeated IDs can be explained by a retry or by manually running both sender examples with the same file. If you see fewer rows, refresh after giving the events time to appear. Check that the time picker includes the stored timestamps, then look for the IDs without the batch filter. That narrows down whether a filter changed a field or whether the event is missing altogether.
If a 202 still gives you no relevant hits, confirm the sender and Discover are looking at the same stack. If the stack uses a custom index name or a LogType route, check the matching index pattern and fields. Inspect the mapping if an exact-match field is absent. Index templates and mappings are managed on Logit.io stacks and can be read for diagnosis. For more checks, follow the guide to diagnosing missing data.
Unlock complete visibility with hosted ELK, Grafana, and Prometheus-backed Observability
Splunk HEC senders
If your sender is already configured for Splunk HEC, follow the Splunk HEC integration guide for the endpoint and setup.
HTTPS batching FAQ
How large can one HTTPS log batch be?
Send 1 to 1,000 events per request with a body of at most 9,800,000 bytes. An individual event also has to fit the limit after serialisation for processing. Measure the outgoing UTF-8 bytes and split before reaching either limit.
Should I send a JSON array or NDJSON?
Use an array when you already have a list of objects in memory. Use NDJSON for line-oriented files or streams. Both send each object as a separate log. Set the content type to match the body you send.
Should I retry the same request after HTTP 413?
Split it into smaller requests. If it is already one event, log and skip it or retain it separately for investigation. An unchanged request still exceeds the reported limit.
Can I get duplicates after HTTP 503?
Yes. Some events can be queued before a 503 is returned. Wait at least as long as Retry-After tells you and keep the same event IDs on replay so you can identify duplicates downstream.
Does HTTP 202 mean I can search the logs immediately?
202 means the events are queued for processing. Check logstash-* in Discover over the relevant @timestamp range to confirm the events appear. For a custom index name or a LogType route, check the matching index pattern and fields.
The Logit.io free trial includes every feature, so you can send a test batch and confirm it in OpenSearch Dashboards. Explore Hosted OpenSearch from Logit.io to see where you can search and investigate the logs your applications send.
