Azure Data Explorer and KQL Interview Questions and Answers Part 5 - Ingestion

Azure Data Explorer Interview Q&A · Part 5 of 10

In this post we are going to cover ingestion in Azure Data Explorer. These are 7 real Azure Data Explorer and KQL interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: ten thousand IoT events a second must land in Azure Data Explorer within a minute.

Ingestion is how data gets into a table: through a data connection, an SDK, a tool or a command. Interviewers like it because most production problems start here: data shows up minutes late, fields land in the wrong columns, or the same file is loaded twice.

Part 5 of the Real Time Azure Data Explorer and KQL Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

Production data arrives by queued ingestion (batched for throughput) or streaming ingestion (sub-second, small data), through Event Hubs, IoT Hub and Event Grid data connections, the SDKs, LightIngest or Data Factory. Mappings put fields in the right columns, the batching policy sets the latency, and extent tags prevent and clean up duplicates.

Let's create some sample data

Every query below runs on the Kusto emulator, Microsoft's Azure Data Explorer engine in a local container, in a database called shop. kql is a small helper that sends a query or a .kql file to the emulator and prints the result as a table. The starting files are four small invented data files, orders, device events and two days of payments, plus setup.kql, which creates the Orders, Events and Payments tables. What only a cluster in Azure can show, such as data connections, sign-in and the ingest endpoint, is shown as code.

orders_1020.csv
OrderId,CustomerId,OrderTime,Amount,Status
1003,C005,2026-10-20T09:15:00Z,35.50,Pending
1004,C001,2026-10-20T12:30:00Z,12.00,Paid
1005,C006,2026-10-20T10:00:00Z,80.00,Paid
events.json
{"ts":"2026-10-20T08:00:00Z","device":{"id":"d1"},"temp":-18.5}
{"ts":"2026-10-20T08:05:00Z","device":{"id":"d2"},"temp":-19.0}
{"ts":"2026-10-20T08:10:00Z","device":{"id":"d3"},"temp":-17.2}
payments_1020.csv
P1,1001,2026-10-20T08:07:00Z,59.90
P2,1002,2026-10-20T11:05:00Z,20.00
P3,1004,2026-10-20T12:31:00Z,12.00
payments_1021.csv
P4,1006,2026-10-21T09:00:00Z,45.00
P5,1007,2026-10-21T10:30:00Z,15.50
P6,1008,2026-10-21T14:10:00Z,99.00
setup.kql
.create table Orders (OrderId:long, CustomerId:string, OrderTime:datetime, Amount:real, Status:string)

.create table Events (Timestamp:datetime, DeviceId:string, Temp:real)

.create table Payments (PaymentId:string, OrderId:long, PaidTime:datetime, Amount:real)

Question 1: Your manager asks how data gets into Azure Data Explorer. What ingestion options do you explain?

Underneath everything there are two modes: queued ingestion, optimized for high throughput, and streaming ingestion, for near real-time latency on small sets of data per table. Every tool sits on top of one of them.

Let's look at the options:

OptionHowUse it for
Event Hubs, IoT Hubdata connection, queued or streamingtelemetry and app events
Event Gridblob created or renamed eventsfiles landing in storage
SDKsqueued, streaming or directyour own apps and services
LightIngestcommand-line tool, ad hocbig one-off and historical loads
Data FactoryCopy activityscheduled pipelines (more latency)
Direct commands.ingest inline / into, .set-or-appendexploration and prototyping only

For streams, Event Hubs and IoT Hub data connections; for files in storage, Event Grid. Apps use the SDKs, LightIngest handles big historical loads, and Data Factory runs scheduled copies, with more latency.

Then there are the direct commands: .ingest inline, .ingest into from a file, and .set-or-append from a query. Let's load two inline rows, the orders_1020.csv file with its header row skipped, and a daily summary into OrdersDaily. Then loaded.kql counts the rows per table.

load.kql
.ingest inline into table Orders <|
1001,C001,2026-10-20T08:05:00Z,59.90,Paid
1002,C003,2026-10-20T11:03:00Z,20.00,Paid

.ingest into table Orders (@"/kustodata/orders_1020.csv")
    with (format="csv", ignoreFirstRecord=true)

.set-or-append OrdersDaily <| Orders
    | summarize Orders = count(), Revenue = sum(Amount)
        by Day = startofday(OrderTime)
loaded.kql
union withsource=Table Orders, OrdersDaily
| summarize Rows = count() by Table
| order by Table asc
Terminal
$ kql -q -f load.kql
> .ingest inline into table Orders <|
ok: .ingest inline into table Orders <|

> .ingest into table Orders (@"/kustodata/orders_1020.csv")
ok: .ingest into table Orders (@"/kustodata/orders_1020.csv")

> .set-or-append OrdersDaily <| Orders
ok: .set-or-append OrdersDaily <| Orders
$ kql -f loaded.kql
> union withsource=Table Orders, OrdersDaily
Table        Rows
-----------  ----
Orders       5
OrdersDaily  1
Result table2 rows
TableRows
Orders5
OrdersDaily1

Orders now has 5 rows, and OrdersDaily has 1. It works, but Microsoft says these commands are for exploration and prototyping only, not production or high-volume scenarios. And ingest from query has no automatic retries.

In a real project, this is how I split it:

  • Production: data connections, SDK queued ingestion
  • History: LightIngest
  • Notebooks and tests: direct commands

That's also why we use direct commands on the emulator.

Question 2: Someone asks the difference between queued and streaming ingestion. When do you use each?

Queued ingestion is the default and is built for throughput. Streaming ingestion writes small requests straight into the table, for latency under a second, and you have to turn it on.

First, queued. Data goes to the cluster's ingest endpoint, waits in a batch, and lands as large, efficient extents. Then streaming. You turn it on for the cluster, then enable the policy on the table or the whole database, and each request is limited to 4 MB:

streaming.kql (Azure, not run)
// 1. cluster: Configurations, Streaming ingestion = On
// 2. then the table (or the whole database):
.alter table Orders policy streamingingestion enable

Now let's try the queued client on the emulator. queued.py builds a QueuedIngestClient for http://localhost:8080 and sends one order row.

queued.py
import io
from azure.kusto.data import KustoConnectionStringBuilder
from azure.kusto.data.data_format import DataFormat
from azure.kusto.ingest import IngestionProperties, QueuedIngestClient

# the emulator has no sign-in (on Azure: Microsoft Entra ID)
kcsb = KustoConnectionStringBuilder.with_no_authentication(
    "http://localhost:8080")
props = IngestionProperties(database="shop", table="Orders",
                            data_format=DataFormat.CSV)
row = b"1006,C002,2026-10-20T13:00:00Z,9.50,Paid\n"
client = QueuedIngestClient(kcsb)
try:
    client.ingest_from_stream(io.BytesIO(row), props)
except Exception as e:
    print(type(e).__name__ + ":", str(e).split("\n")[0])
Terminal
$ python queued.py
KustoApiError: Cannot get ingestion resources from this service endpoint. The appropriate endpoint is
  most likely 'http://ingest-localhost:8080/'.

It fails with Cannot get ingestion resources from this service endpoint, and the error points at where it should go: http://ingest-localhost:8080/. The emulator has no ingest endpoint. In Azure, the same client points at your cluster's ingest- URI, signs in with Microsoft Entra ID, and works:

queued_azure.py (Azure, not run)
# Azure: queued ingestion goes to the ingest- URI
ingest = "https://ingest-mycluster.westeurope.kusto.windows.net"
kcsb = KustoConnectionStringBuilder.with_az_cli_authentication(
    ingest)                          # Microsoft Entra ID
client = QueuedIngestClient(kcsb)
client.ingest_from_file("new_orders.csv", props)   # no header row

Here is when we pick each one:

Queued (default)Streaming
built forhigh throughput, large extentslatency under a second, small data
setupnothing extracluster setting, then a table or database policy
limitsbatching policy: 5 min or 1 GB by default4 MB per request
a table over 4 GB per houruse itconsider queued instead
extent tagssupportednot supported
mappingspre-created or inlinepre-created only

Use streaming for sub-second latency, or for many tables with a small stream each. Over 4 GB an hour per table, consider queued. And streaming can't set extent tags, and it needs pre-created mappings.

My default

Queued with a shorter batching time. Streaming only when the business needs seconds, because it uses local SSD and reduces the hot cache.

Question 3: A teammate's JSON files land with fields in the wrong columns. How do ingestion mappings work?

A mapping says which source field goes into which column. For JSON, each column gets a path, like $.ts. Without one, an identity mapping matches names exactly, case-sensitive, and anything that doesn't match loads as an empty column.

Our device events in events.json have ts, device.id and temp, but the Events table has Timestamp, DeviceId and Temp. Let's ingest the file without a mapping and count the empty values.

Terminal
$ kql -q '.ingest into table Events (@"/kustodata/events.json") with (format="json")'
ok: .ingest into table Events (@"/kustodata/events.json") with (format="json")
$ kql "Events | summarize Rows = count(), NoTime = countif(isnull(Timestamp)), NoTemp = countif(isnull(Temp))"
Rows  NoTime  NoTemp
----  ------  ------
3     3       3

3 rows land, and NoTime and NoTemp are both 3. Every row is empty, and there is no error.

Now let's fix it. map.kql clears the bad rows, creates a JSON mapping called EventsMap on the table, and references it by name with ingestionMappingReference. Then we read the table back.

map.kql
.clear table Events data

.create table Events ingestion json mapping "EventsMap"
```
[
  {"column": "Timestamp", "Properties": {"Path": "$.ts"}},
  {"column": "DeviceId",  "Properties": {"Path": "$.device.id"}},
  {"column": "Temp",      "Properties": {"Path": "$.temp"}}
]
```

.ingest into table Events (@"/kustodata/events.json")
    with (format="json", ingestionMappingReference="EventsMap")
Terminal
$ kql -q -f map.kql
> .clear table Events data
ok: .clear table Events data

> .create table Events ingestion json mapping "EventsMap"
ok: .create table Events ingestion json mapping "EventsMap"

> .ingest into table Events (@"/kustodata/events.json")
ok: .ingest into table Events (@"/kustodata/events.json")
$ kql "Events | order by Timestamp asc"
Timestamp             DeviceId  Temp
--------------------  --------  -----
2026-10-20T08:00:00Z  d1        -18.5
2026-10-20T08:05:00Z  d2        -19
2026-10-20T08:10:00Z  d3        -17.2
Result table3 rows
TimestampDeviceIdTemp
2026-10-20T08:00:00Zd1-18.5
2026-10-20T08:05:00Zd2-19
2026-10-20T08:10:00Zd3-17.2

The same file lands with the time, the device and the temperature in the right columns: d1 at 2026-10-20T08:00:00Z with -18.5, then d2 with -19 and d3 with -17.2.

Mappings also cover CSV by ordinal, Parquet and Avro, and transformations such as DateTimeFromUnixSeconds.

Real project

Pre-create the mappings, because streaming and data connections reference them by name. And since mapping mistakes are silent, run a null check on key columns when a new source goes live.

Question 4: Someone asks why new data takes minutes to appear. How does the ingestion batching policy work?

Queued data waits in a batch until the batch is sealed by the first limit it reaches: time, size or number of items. By default that's 5 minutes or 1 GB.

  • Ingest request: queued
  • Batch: time, size, item count
  • Sealed: the first limit reached
  • Extent: queryable

So a quiet table often waits the full five minutes, plus processing time. That's the delay your teammate sees, and it's by design: big batches make efficient extents.

batch.kql reads the effective policy on Events, sets 30 seconds, reads it back, then tries 5 seconds and one hour. We run it with -e, so the file carries on after an error.

batch.kql
.show table Events details
| extend p = parse_json(IngestionBatchingPolicy)
| project Time = tostring(p.MaximumBatchingTimeSpan),
    SizeMB = tolong(p.MaximumRawDataSizeMB)

.alter table Events policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "00:00:30"}'
| project PolicyName, EntityName

.show table Events policy ingestionbatching
| extend p = parse_json(Policy)
| project EntityName, Time = tostring(p.MaximumBatchingTimeSpan)

.alter table Events policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "00:00:05"}'

.alter table Events policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "01:00:00"}'
Terminal
$ kql -e -f batch.kql
> .show table Events details
Time      SizeMB
--------  ------
00:05:00  1024

> .alter table Events policy ingestionbatching
PolicyName               EntityName
-----------------------  ---------------
IngestionBatchingPolicy  [shop].[Events]

> .show table Events policy ingestionbatching
EntityName       Time
---------------  --------
[shop].[Events]  00:00:30

> .alter table Events policy ingestionbatching
Error: Error during execution of a policy operation: MaximumBatchingTimeSpan should be greater than or
  equal to 00:00:10

> .alter table Events policy ingestionbatching
Error: Error during execution of a policy operation: MaximumBatchingTimeSpan should be lower than or
  equal to 00:30:00

The default is 00:05:00 and 1024 MB. Our 30 seconds is stored: [shop].[Events] now shows 00:00:30. The engine checks the range: five seconds is refused, it should be greater than or equal to 00:00:10, and one hour too, it should be lower than or equal to 00:30:00.

MaximumBatchingTimeSpanMeaning
00:05:00the default
00:00:20 to 00:00:30the documented low-latency setting
under thatmore cost, can increase end-to-end latency
00:00:10 / 00:30:00the minimum / the maximum

Microsoft's low-latency setting is 20 to 30 seconds. Going lower costs more, and can even increase end-to-end latency. Set it per table, or on the whole database.

Emulator

The policy is stored and validated, but there is no queued ingestion to batch. In Azure, confirm the effect with the Ingestion latency metric.

Question 5: A teammate asks how to ingest from Event Hubs. How do you set up the data connection?

The data connection belongs to the database. It reads one event hub through its own consumer group, and ingests into a target table with a format and a mapping.

The flow looks like this:

  • Producers: apps and devices
  • Event hub: partitions
  • Consumer group: one per connection
  • Data connection: table, format, mapping

The setup takes four steps. First, a dedicated consumer group: it must be unique per consumer. Second, give the cluster's managed identity the Azure Event Hubs Data Receiver role on the event hub; managed identity is the recommended way. Third, a managed identity policy on the database that allows data connections. Fourth, the connection itself, with the table, the JSON format and the pre-created mapping. The emulator has no data connections, so this is code:

data_connection.sh (Azure, not run)
# 1. a dedicated consumer group for this connection
az eventhubs eventhub consumer-group create -g rg-iot \
  --namespace-name ehns-iot --eventhub-name telemetry \
  --name adx-iotraw
# 2. the cluster identity may read the event hub
az role assignment create --role "Azure Event Hubs Data Receiver" \
  --assignee-object-id "$CLUSTER_PRINCIPAL_ID" \
  --assignee-principal-type ServicePrincipal --scope "$EH_ID"
# 3. in the database (KQL): allow the identity for data connections
#  .alter database iot policy managed_identity
#  ```[{"ObjectId": "system", "AllowedUsages": "DataConnection"}]```
# 4. the data connection (kusto extension, experimental)
az kusto data-connection event-hub create -g rg-iot \
  --cluster-name adx-iot --database-name iot --location westeurope \
  --name telemetry-to-iotraw --event-hub-resource-id "$EH_ID" \
  --consumer-group adx-iotraw --managed-identity "$CLUSTER_ID" \
  --table-name IotRaw --data-format JSON \
  --mapping-rule-name IotMap

The connection only picks up events enqueued after it's created, unless you set a retrieval start date.

Producers can override the connection's defaults per event with the Table, Format and IngestionMappingReference properties, so one event hub can feed several tables:

producer.py (Azure, not run)
import json
from azure.eventhub import EventData
# producer: an EventHubProducerClient for the "telemetry" hub

event = EventData(json.dumps(reading))
event.properties = {               # override the connection
    "Table": "IotRaw",
    "Format": "json",
    "IngestionMappingReference": "IotMap",
}
producer.send_batch([event])

You can also ingest system properties, such as x-opt-enqueued-time.

Pitfalls

Uneven partitions raise discovery latency, and events that can't be processed show up as ingestion failures.

Question 6: A load ingested the same file twice. How do you prevent and clean up duplicates?

Clean up with extent tags, prevent with ingest-by tags, and keep a query-time safety net.

twice.kql loads payments_1020.csv two times, and each load carries its own drop-by tag, run1 and run2. Then copies.kql counts the copies per payment.

twice.kql
.ingest into table Payments (@"/kustodata/payments_1020.csv")
    with (format="csv", tags='["drop-by:run1"]')

.ingest into table Payments (@"/kustodata/payments_1020.csv")
    with (format="csv", tags='["drop-by:run2"]')
copies.kql
Payments
| where PaidTime between (datetime(2026-10-20) .. 1d)
| summarize Copies = count(), Amount = sum(Amount) by PaymentId
| order by PaymentId asc
Terminal
$ kql -q -f twice.kql
> .ingest into table Payments (@"/kustodata/payments_1020.csv")
ok: .ingest into table Payments (@"/kustodata/payments_1020.csv")

> .ingest into table Payments (@"/kustodata/payments_1020.csv")
ok: .ingest into table Payments (@"/kustodata/payments_1020.csv")
$ kql -f copies.kql
> Payments
PaymentId  Copies  Amount
---------  ------  ------
P1         2       119.8
P2         2       40
P3         2       24
Result table3 rows
PaymentIdCopiesAmount
P12119.8
P2240
P3224

Every payment has 2 copies, and P1 shows 119.8, twice its real amount.

Because each load has its own tag, the cleanup is one command: drop the extents tagged drop-by:run2.

clean.kql
.drop extents <|
    .show table Payments extents where tags has "drop-by:run2"
Terminal
$ kql -q -f clean.kql
> .drop extents <|
ok: .drop extents <|
$ kql -f copies.kql
> Payments
PaymentId  Copies  Amount
---------  ------  ------
P1         1       59.9
P2         1       20
P3         1       12
KQL - the query behind the result table
Payments
| where PaidTime between (datetime(2026-10-20) .. 1d)
| summarize Copies = count(), Amount = sum(Amount) by PaymentId
| order by PaymentId asc
Result table3 rows
PaymentIdCopiesAmount
P1159.9
P2120
P3112

Each payment has 1 copy again, and P1 is back to 59.9.

To prevent it, tag the load ingest-by with the file name and add ingestIfNotExists with the same value. safe.kql loads payments_1021.csv twice this way, and perday.kql counts the rows per day.

safe.kql
.ingest into table Payments (@"/kustodata/payments_1021.csv")
    with (format="csv", tags='["ingest-by:payments_1021"]',
          ingestIfNotExists='["payments_1021"]')

.ingest into table Payments (@"/kustodata/payments_1021.csv")
    with (format="csv", tags='["ingest-by:payments_1021"]',
          ingestIfNotExists='["payments_1021"]')
perday.kql
Payments
| extend Day = format_datetime(PaidTime, "yyyy-MM-dd")
| summarize Rows = count() by Day
| order by Day asc
Terminal
$ kql -q -f safe.kql
> .ingest into table Payments (@"/kustodata/payments_1021.csv")
ok: .ingest into table Payments (@"/kustodata/payments_1021.csv")

> .ingest into table Payments (@"/kustodata/payments_1021.csv")
ok: .ingest into table Payments (@"/kustodata/payments_1021.csv")
$ kql -f perday.kql
> Payments
Day         Rows
----------  ----
2026-10-20  3
2026-10-21  3
Result table2 rows
DayRows
2026-10-203
2026-10-213

Both loads print ok, but 2026-10-21 has 3 rows, not six. The second load was skipped. Careful: the skipped load looks like a normal success, with HasErrors false, so prove the skip with a count.

Without a tag:

  • .delete table T records: only if the filter tells the copies apart, like ingestion time; a plain filter deletes both
  • arg_max(..., *) by key: deduplicate at query time
  • a take_any() materialized view: deduplicate as data arrives
Real project

Unique ingest-by or drop-by tags on every small call hurt performance, so I use them for a few large batches. And I fix the retry upstream.

Scenario 7: Ten thousand IoT events per second must land in Azure Data Explorer within a minute. How do you design it?

Size it first. Then it's queued ingestion through a data connection, into a raw table with a 30-second batching policy.

Let's do the sizing in KQL. sizing.kql assumes about 1 KB per event; measure yours.

sizing.kql
let eventsPerSecond = 10000;
let bytesPerEvent = 1000;    // assumed average: measure yours
print PerMinute = eventsPerSecond * 60,
    MBPerSecond = eventsPerSecond * bytesPerEvent / 1e6,
    GBPerHour = eventsPerSecond * bytesPerEvent * 3600 / 1e9
Terminal
$ kql -f sizing.kql
> let eventsPerSecond = 10000;
PerMinute  MBPerSecond  GBPerHour
---------  -----------  ---------
600000     10           36
Result table1 row
PerMinuteMBPerSecondGBPerHour
6000001036

That's 600000 events a minute, 10 MB a second, or 36 GB an hour, into one table. Far above 4 GB an hour, so queued, not streaming.

Here is the design:

  • Devices: 10,000 events a second
  • IoT Hub or Event Hubs: 10 or more throughput units and partitions
  • Data connection: its own consumer group
  • IotRaw: queued, 30-second batches
  • Typed tables: an update policy

On Event Hubs Standard, one throughput unit takes 1 MB or 1,000 events a second, so 10 MB a second needs ten or more. The connection uses a managed identity; IoT Hub uses a shared access policy.

Then the minute. The default policy misses it: at 10 MB a second, 1 GB takes about a hundred seconds. So the raw table gets 30 seconds, about 300 MB per batch, well under the 1 GB limit.

On the emulator, we create the raw table with the whole event in a dynamic column, its JSON mapping, and the 30-second policy: the same commands we deploy.

iot.kql
.create table IotRaw (DeviceId:string, Ts:datetime, Temp:real,
    Raw:dynamic)

.create table IotRaw ingestion json mapping "IotMap"
```
[
  {"column": "DeviceId", "Properties": {"Path": "$.deviceId"}},
  {"column": "Ts",       "Properties": {"Path": "$.ts"}},
  {"column": "Temp",     "Properties": {"Path": "$.temp"}},
  {"column": "Raw",      "Properties": {"Path": "$"}}
]
```

.alter table IotRaw policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "00:00:30"}'
iotshow.kql
.show table IotRaw policy ingestionbatching
| extend p = parse_json(Policy)
| project EntityName, Time = tostring(p.MaximumBatchingTimeSpan)
Terminal
$ kql -q -f iot.kql
> .create table IotRaw (DeviceId:string, Ts:datetime, Temp:real,
ok: .create table IotRaw (DeviceId:string, Ts:datetime, Temp:real,

> .create table IotRaw ingestion json mapping "IotMap"
ok: .create table IotRaw ingestion json mapping "IotMap"

> .alter table IotRaw policy ingestionbatching
ok: .alter table IotRaw policy ingestionbatching
$ kql -f iotshow.kql
> .show table IotRaw policy ingestionbatching
EntityName       Time
---------------  --------
[shop].[IotRaw]  00:00:30

[shop].[IotRaw] shows 00:00:30. An update policy adds the typed tables later.

Then we prove it in Azure:

  • Ingestion latency and discovery latency: metrics, against the 1-minute goal
  • Alerts on ingestion failures: events that can't be processed land there
  • A load test at peak: before go-live

Key points to remember

  • Two modes: queued for throughput, streaming for sub-second latency on small data
  • Direct commands (.ingest inline / into, .set-or-append) are for exploration and prototyping only
  • Mappings put source fields in columns; identity mapping is by exact name, mistakes are silent
  • The batching policy seals a batch on time, size or item count: 5 minutes or 1 GB by default
  • Duplicates: drop-by tags to clean up, ingest-by plus ingestIfNotExists to prevent

The full script

Here is a Python script that writes every file and runs every query in order on the Kusto emulator; start the emulator container first, as the comments at the top of the script show, and for queued.py in question 2 run pip install azure-kusto-data azure-kusto-ingest.

Show the full script that writes the files and runs every step
Full script - writes the files and runs every step on the Kusto emulator (start the emulator container first, see the comments at the top), run it with Python
# ========================================================================
# Azure Data Explorer Interview Q&A #5 - Ingestion
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run on the Kusto emulator (Kustainer, the Azure Data Explorer engine in a Linux container,
# build 2026.11.02); the outputs in the video and the blog post are the real outputs.
# To run it yourself (Docker on Linux, macOS or Windows with WSL), in an EMPTY folder:
#   1. Start the emulator with this folder mounted at /kustodata (the steps ingest files from there):
#      docker run -d --name kustainer -e ACCEPT_EULA=Y -m 4G -p 8080:8080 -v "$PWD":/kustodata \
#          mcr.microsoft.com/azuredataexplorer/kustainer-linux:latest
#      Wait until `docker logs kustainer` says the database "is answering queries".
#   2. python KQL_Interview_QA_05_Code.py   (Python 3.10 or later; kql.py itself needs no packages: it uses the REST API)
#      The python scripts in some steps use the Kusto Python SDK: pip install azure-kusto-data azure-kusto-ingest
# "kql" in the commands is a small helper written by Step 0 (kql.py): it sends a query or a management command
# to http://localhost:8080 and prints the result as a text table (no sign-in: the emulator has no authentication).
# The emulator is for development and testing only; an Azure Data Explorer cluster needs Microsoft Entra ID sign-in
# (use the Kusto SDK or the web UI there).
# Steps that restart the emulator say so in a comment: run "docker restart kustainer" at that point.
# ========================================================================

import os, subprocess, sys, time

def write(path, text):
    if text is None:
        if os.path.exists(path): os.remove(path)
        return
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def run(cmd, expect_error=False, allow_error=False, env=None):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
    if rc != 0 and not (expect_error or allow_error):
        raise SystemExit("stopped: this command was expected to succeed")

# Environment used by every step (the database the steps use)
os.environ.update({'KQL_DB': 'shop'})

# Step 0: the kql helper, the database and the starting files
write("kql.py", '"""kql: run KQL queries and management commands on the local Kusto emulator (Kustainer), print the results as text tables.\n  kql \'StormEvents | take 3\'              run one query or one management command (starts with \'.\')\n  kql -f script.kql                      run every statement in the file (statements are separated by blank lines;\n                                         // comment lines are skipped); each result is printed under its first line\n  options: -d DB (default $KQL_DB or NetDefaultDB)  --max N rows to print (default 30)  --cell N max chars per cell (default 60)\n           -q  for management commands: print one line ("ok: <command>") instead of the result table\n           --stats  after a query, print the rows / extents the query scanned (from the engine\'s own query statistics)\n           --props \'{"Options": {...}}\'  client request properties (e.g. truncationmaxrecords)\n           -e  keep going after an error (the error is printed and the exit code is 1 at the end)\n           --json  print the last statement\'s first result as JSON {"cols": [...], "rows": [...]} (used by the video generator)\nEmpty cells: a null value in a non-string column prints as "null"; an empty or null string prints as nothing.\nA query that fails after returning some rows (for example a result over the truncation limit) prints the rows it got, then\n"Error (partial result): <engine message>", and exits 1.\nThe engine answers at http://localhost:8080 (no authentication: the emulator has none)."""\nimport json, os, re, sys, urllib.request, urllib.error\n\nURL = os.environ.get(\'KQL_URL\', \'http://localhost:8080\')\n\n\ndef post(path, db, csl, props=None):\n    body = {\'db\': db, \'csl\': csl, \'properties\': json.dumps(props or {\'Options\': {}})}\n    req = urllib.request.Request(URL + path, data=json.dumps(body).encode(), method=\'POST\',\n                                 headers={\'Content-Type\': \'application/json; charset=utf-8\', \'Accept\': \'application/json\',\n                                          \'x-ms-app\': \'kql-cli\', \'x-ms-client-request-id\': \'kql-cli\'})\n    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))\n    try:\n        with opener.open(req, timeout=600) as r: return json.loads(r.read().decode(\'utf-8\'))\n    except urllib.error.HTTPError as e:\n        txt = e.read().decode(\'utf-8\', \'replace\')\n        try:\n            er = json.loads(txt)[\'error\']\n            msg = er.get(\'@message\') or er.get(\'message\')\n        except Exception:\n            msg = txt.strip().split(\'\\n\')[0]\n        msg = re.sub(r\'^Request is invalid and cannot be processed: \', \'\', msg)\n        msg = re.sub(r\'\\s*\\(Activity stack:.*\', \'\', msg, flags=re.S)\n        raise KqlError(msg.strip())\n\n\nclass KqlError(Exception): pass\n\n\ndef cell(v, width, typ=\'\'):\n    if v is None: s = \'\' if typ in (\'string\', \'\') else \'null\'\n    elif isinstance(v, bool): s = \'true\' if v else \'false\'\n    elif isinstance(v, (dict, list)): s = json.dumps(v, separators=(\',\', \':\'), ensure_ascii=False)\n    elif isinstance(v, float):\n        s = repr(v)\n        if s.endswith(\'.0\'): s = s[:-2]\n    else: s = str(v)\n    s = s.replace(\'\\r\', \' \').replace(\'\\n\', \' \')\n    if len(s) > width: s = s[:width - 3] + \'...\'\n    return s\n\n\ndef table(cols, rows, mx, width, types=None):\n    rows = rows if isinstance(rows, list) else []\n    types = types or [\'\'] * len(cols)\n    shown = [[cell(v, width, types[i]) for i, v in enumerate(r)] for r in rows[:mx]]\n    w = [max([len(c)] + [len(r[i]) for r in shown]) for i, c in enumerate(cols)]\n    out = [\'  \'.join(c.ljust(w[i]) for i, c in enumerate(cols)).rstrip(),\n           \'  \'.join(\'-\' * w[i] for i in range(len(cols)))]\n    for r in shown:\n        out.append(\'  \'.join(v.ljust(w[i]) for i, v in enumerate(r)).rstrip())\n    n = len(rows)\n    if n > mx: out.append(\'... %d more rows (%d rows in total)\' % (n - mx, n))\n    elif n == 0: out.append(\'(no rows)\')\n    return \'\\n\'.join(out)\n\n\nLAST = {}\n\n\ndef one_api_msg(errs):\n    msgs = []\n    for e in errs or []:\n        er = e.get(\'error\', e) if isinstance(e, dict) else {}\n        m = er.get(\'@message\') or er.get(\'message\') or str(e)\n        m = re.sub(r\'\\s*\\(Activity stack:.*\', \'\', m, flags=re.S).strip()\n        if m not in msgs: msgs.append(m)\n    return \' | \'.join(msgs) or \'unknown error\'\n\n\ndef run_query(db, csl, a):\n    frames = post(\'/v2/rest/query\', db, csl, a.props)\n    outs, stats, partial = [], None, None\n    for f in frames:\n        if f.get(\'FrameType\') == \'DataSetCompletion\' and f.get(\'HasErrors\') and partial is None:\n            partial = one_api_msg(f.get(\'OneApiErrors\'))\n        if f.get(\'FrameType\') != \'DataTable\': continue\n        if f.get(\'TableKind\') == \'PrimaryResult\':\n            rows = [r for r in f[\'Rows\'] if isinstance(r, list)]\n            for r in f[\'Rows\']:\n                if isinstance(r, dict) and r.get(\'OneApiErrors\'): partial = one_api_msg(r[\'OneApiErrors\'])\n            cols = [c[\'ColumnName\'] for c in f[\'Columns\']]\n            if \'cols\' not in LAST: LAST.update(cols=cols, rows=rows)\n            outs.append(table(cols, rows, a.max, a.cell, [str(c.get(\'ColumnType\', \'\')).lower() for c in f[\'Columns\']]))\n        if f.get(\'TableKind\') == \'QueryCompletionInformation\':\n            cols = [c[\'ColumnName\'] for c in f[\'Columns\']]\n            for r in f[\'Rows\']:\n                d = dict(zip(cols, r))\n                if d.get(\'EventTypeName\') == \'QueryResourceConsumption\':\n                    try: stats = json.loads(d[\'Payload\'])\n                    except Exception: pass\n                if d.get(\'Level\') in (2, 3) and d.get(\'EventTypeName\') not in (\'QueryResourceConsumption\',):\n                    txt = d.get(\'Payload\') or \'\'\n                    try: txt = json.loads(txt).get(\'Text\', txt)\n                    except Exception: pass\n                    outs.append(\'%s: %s\' % (\'Warning\' if d.get(\'Level\') == 3 else \'Error\', txt))\n    if a.stats and stats:\n        sh = (stats.get(\'resource_usage\') or {}).get(\'cache\', {}).get(\'shards\', {})\n        ix = stats.get(\'input_dataset_statistics\') or {}\n        ex, rw = ix.get(\'extents\') or {}, ix.get(\'rows\') or {}\n        outs.append(\'scanned: %s of %s extents, %s of %s rows\' % (ex.get(\'scanned\'), ex.get(\'total\'), rw.get(\'scanned\'), rw.get(\'total\')))\n    if partial:\n        outs.append(\'Error (partial result): \' + partial)\n        raise PartialError(\'\\n\\n\'.join(outs))\n    return \'\\n\\n\'.join(outs)\n\n\nclass PartialError(Exception): pass\n\n\ndef run_mgmt(db, csl, a):\n    d = post(\'/v1/rest/mgmt\', db, csl, a.props)\n    if a.q and not a.json: return \'ok: \' + first_line(csl)\n    t = (d.get(\'Tables\') or [{}])[0]\n    LAST.update(cols=[c[\'ColumnName\'] for c in t.get(\'Columns\', [])], rows=t.get(\'Rows\', []))\n    return table([c[\'ColumnName\'] for c in t.get(\'Columns\', [])], t.get(\'Rows\', []), a.max, a.cell,\n                 [str(c.get(\'DataType\', c.get(\'ColumnType\', \'\'))).lower().replace(\'system.\', \'\') for c in t.get(\'Columns\', [])])\n\n\ndef first_line(s):\n    l = s.strip().split(\'\\n\')[0].strip()\n    return l if len(l) <= 90 else l[:87] + \'...\'\n\n\ndef statements(text):\n    blocks, cur = [], []\n    for l in text.split(\'\\n\'):\n        if not l.strip():\n            if cur: blocks.append(\'\\n\'.join(cur)); cur = []\n            continue\n        if l.strip().startswith(\'//\') and not cur: continue\n        cur.append(l)\n    if cur: blocks.append(\'\\n\'.join(cur))\n    return blocks\n\n\ndef main():\n    import argparse\n    p = argparse.ArgumentParser(add_help=False)\n    p.add_argument(\'-d\', default=os.environ.get(\'KQL_DB\', \'NetDefaultDB\'))\n    p.add_argument(\'-f\'); p.add_argument(\'-q\', action=\'store_true\'); p.add_argument(\'-e\', action=\'store_true\')\n    p.add_argument(\'--stats\', action=\'store_true\'); p.add_argument(\'--max\', type=int, default=30)\n    p.add_argument(\'--cell\', type=int, default=60); p.add_argument(\'--props\'); p.add_argument(\'-h\', \'--help\', action=\'store_true\')\n    p.add_argument(\'--json\', action=\'store_true\')\n    p.add_argument(\'text\', nargs=\'?\')\n    a = p.parse_args()\n    if a.help or (not a.f and not a.text): print(__doc__); return 0\n    a.props = json.loads(a.props) if a.props else None\n    stmts = statements(open(a.f).read()) if a.f else [a.text]\n    rc, first = 0, True\n    if a.json:\n        for s in stmts:\n            LAST.clear()\n            try:\n                run_mgmt(a.d, s, a) if s.lstrip().startswith(\'.\') else run_query(a.d, s, a)\n            except (KqlError, PartialError) as e:\n                print(\'Error: \' + str(e)); return 1\n        print(json.dumps(dict(cols=LAST.get(\'cols\', []), rows=LAST.get(\'rows\', [])), ensure_ascii=False))\n        return 0\n    for s in stmts:\n        if a.f:\n            if not first: print()\n            print(\'> \' + first_line(s))\n        first = False\n        try:\n            out = run_mgmt(a.d, s, a) if s.lstrip().startswith(\'.\') else run_query(a.d, s, a)\n            if out: print(out)\n        except PartialError as e:\n            print(str(e)); rc = 1\n            if not a.e: return 1\n        except KqlError as e:\n            print(\'Error: \' + str(e)); rc = 1\n            if not a.e: return 1\n    return rc\n\n\nif __name__ == \'__main__\':\n    sys.exit(main())\n')
KQL = '"%s" "%s"' % (sys.executable, os.path.abspath("kql.py"))   # commands below run it as: python kql.py ...
run(KQL + ' -d NetDefaultDB -q \'.create database shop persist (@"/kustodata/dbs/shop/md", @"/kustodata/dbs/shop/data")\'')
write('orders_1020.csv', """\
OrderId,CustomerId,OrderTime,Amount,Status
1003,C005,2026-10-20T09:15:00Z,35.50,Pending
1004,C001,2026-10-20T12:30:00Z,12.00,Paid
1005,C006,2026-10-20T10:00:00Z,80.00,Paid
""")
write('events.json', """\
{"ts":"2026-10-20T08:00:00Z","device":{"id":"d1"},"temp":-18.5}
{"ts":"2026-10-20T08:05:00Z","device":{"id":"d2"},"temp":-19.0}
{"ts":"2026-10-20T08:10:00Z","device":{"id":"d3"},"temp":-17.2}
""")
write('payments_1020.csv', """\
P1,1001,2026-10-20T08:07:00Z,59.90
P2,1002,2026-10-20T11:05:00Z,20.00
P3,1004,2026-10-20T12:31:00Z,12.00
""")
write('payments_1021.csv', """\
P4,1006,2026-10-21T09:00:00Z,45.00
P5,1007,2026-10-21T10:30:00Z,15.50
P6,1008,2026-10-21T14:10:00Z,99.00
""")
write('setup.kql', """\
.create table Orders (OrderId:long, CustomerId:string, OrderTime:datetime, Amount:real, Status:string)

.create table Events (Timestamp:datetime, DeviceId:string, Temp:real)

.create table Payments (PaymentId:string, OrderId:long, PaidTime:datetime, Amount:real)
""")
run(KQL + ' -q -f setup.kql')

# Step 1: Direct commands: .ingest inline, .ingest into a file, .set-or-append from a query
write('load.kql', """\
.ingest inline into table Orders <|
1001,C001,2026-10-20T08:05:00Z,59.90,Paid
1002,C003,2026-10-20T11:03:00Z,20.00,Paid

.ingest into table Orders (@"/kustodata/orders_1020.csv")
    with (format="csv", ignoreFirstRecord=true)

.set-or-append OrdersDaily <| Orders
    | summarize Orders = count(), Revenue = sum(Amount)
        by Day = startofday(OrderTime)
""")
write('loaded.kql', """\
union withsource=Table Orders, OrdersDaily
| summarize Rows = count() by Table
| order by Table asc
""")
run(KQL + ' -q -f load.kql')
run(KQL + ' -f loaded.kql')

# Step 2: The queued ingest client on the emulator: no ingest endpoint
write('queued.py', 'import io\nfrom azure.kusto.data import KustoConnectionStringBuilder\nfrom azure.kusto.data.data_format import DataFormat\nfrom azure.kusto.ingest import IngestionProperties, QueuedIngestClient\n\n# the emulator has no sign-in (on Azure: Microsoft Entra ID)\nkcsb = KustoConnectionStringBuilder.with_no_authentication(\n    "http://localhost:8080")\nprops = IngestionProperties(database="shop", table="Orders",\n                            data_format=DataFormat.CSV)\nrow = b"1006,C002,2026-10-20T13:00:00Z,9.50,Paid\\n"\nclient = QueuedIngestClient(kcsb)\ntry:\n    client.ingest_from_stream(io.BytesIO(row), props)\nexcept Exception as e:\n    print(type(e).__name__ + ":", str(e).split("\\n")[0])\n')
run('python queued.py')

# Step 3: JSON without a mapping: rows land, every column empty, no error
run(KQL + ' -q \'.ingest into table Events (@"/kustodata/events.json") with (format="json")\'')
run(KQL + ' "Events | summarize Rows = count(), NoTime = countif(isnull(Timestamp)), NoTemp = countif(isnull(Temp))"')

# Step 4: A JSON mapping with paths, referenced by name
write('map.kql', """\
.clear table Events data

.create table Events ingestion json mapping "EventsMap"
```
[
  {"column": "Timestamp", "Properties": {"Path": "$.ts"}},
  {"column": "DeviceId",  "Properties": {"Path": "$.device.id"}},
  {"column": "Temp",      "Properties": {"Path": "$.temp"}}
]
```

.ingest into table Events (@"/kustodata/events.json")
    with (format="json", ingestionMappingReference="EventsMap")
""")
run(KQL + ' -q -f map.kql')
run(KQL + ' "Events | order by Timestamp asc"')

# Step 5: The batching policy: the default, 30 seconds, and the allowed range
write('batch.kql', """\
.show table Events details
| extend p = parse_json(IngestionBatchingPolicy)
| project Time = tostring(p.MaximumBatchingTimeSpan),
    SizeMB = tolong(p.MaximumRawDataSizeMB)

.alter table Events policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "00:00:30"}'
| project PolicyName, EntityName

.show table Events policy ingestionbatching
| extend p = parse_json(Policy)
| project EntityName, Time = tostring(p.MaximumBatchingTimeSpan)

.alter table Events policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "00:00:05"}'

.alter table Events policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "01:00:00"}'
""")
run(KQL + ' -e -f batch.kql', allow_error=True)

# Step 6: The same file loaded twice
write('twice.kql', """\
.ingest into table Payments (@"/kustodata/payments_1020.csv")
    with (format="csv", tags='["drop-by:run1"]')

.ingest into table Payments (@"/kustodata/payments_1020.csv")
    with (format="csv", tags='["drop-by:run2"]')
""")
write('copies.kql', """\
Payments
| where PaidTime between (datetime(2026-10-20) .. 1d)
| summarize Copies = count(), Amount = sum(Amount) by PaymentId
| order by PaymentId asc
""")
run(KQL + ' -q -f twice.kql')
run(KQL + ' -f copies.kql')

# Step 7: Clean up: drop the extents tagged drop-by:run2
write('clean.kql', """\
.drop extents <|
    .show table Payments extents where tags has "drop-by:run2"
""")
run(KQL + ' -q -f clean.kql')
run(KQL + ' -f copies.kql')

# Step 8: Prevent: ingest-by tag plus ingestIfNotExists, loaded twice
write('safe.kql', """\
.ingest into table Payments (@"/kustodata/payments_1021.csv")
    with (format="csv", tags='["ingest-by:payments_1021"]',
          ingestIfNotExists='["payments_1021"]')

.ingest into table Payments (@"/kustodata/payments_1021.csv")
    with (format="csv", tags='["ingest-by:payments_1021"]',
          ingestIfNotExists='["payments_1021"]')
""")
write('perday.kql', """\
Payments
| extend Day = format_datetime(PaidTime, "yyyy-MM-dd")
| summarize Rows = count() by Day
| order by Day asc
""")
run(KQL + ' -q -f safe.kql')
run(KQL + ' -f perday.kql')

# Step 9: Sizing the IoT stream
write('sizing.kql', """\
let eventsPerSecond = 10000;
let bytesPerEvent = 1000;    // assumed average: measure yours
print PerMinute = eventsPerSecond * 60,
    MBPerSecond = eventsPerSecond * bytesPerEvent / 1e6,
    GBPerHour = eventsPerSecond * bytesPerEvent * 3600 / 1e9
""")
run(KQL + ' -f sizing.kql')

# Step 10: The raw IoT table, its JSON mapping and a 30-second batching policy
write('iot.kql', """\
.create table IotRaw (DeviceId:string, Ts:datetime, Temp:real,
    Raw:dynamic)

.create table IotRaw ingestion json mapping "IotMap"
```
[
  {"column": "DeviceId", "Properties": {"Path": "$.deviceId"}},
  {"column": "Ts",       "Properties": {"Path": "$.ts"}},
  {"column": "Temp",     "Properties": {"Path": "$.temp"}},
  {"column": "Raw",      "Properties": {"Path": "$"}}
]
```

.alter table IotRaw policy ingestionbatching
    '{"MaximumBatchingTimeSpan": "00:00:30"}'
""")
write('iotshow.kql', """\
.show table IotRaw policy ingestionbatching
| extend p = parse_json(Policy)
| project EntityName, Time = tostring(p.MaximumBatchingTimeSpan)
""")
run(KQL + ' -q -f iot.kql')
run(KQL + ' -f iotshow.kql')
Next in this series

Part 6: Table Design and Policies

The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on the Kusto emulator (Kustainer, the Azure Data Explorer engine in a Linux container, build 2026.11.02). Features the emulator cannot show truthfully are shown as code. Part of the Real Time Azure Data Explorer and KQL Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of November 2026; check the official Azure Data Explorer and Kusto documentation (learn.microsoft.com/azure/data-explorer and learn.microsoft.com/kusto) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.