API-performance analysis in BC with KQL

API-performance in Business Central
API-performance in Business Central

API-performance analysis in Business Central with KQL. With this guide, any consultant can independently analyse performance using Application Insights. First, you always run one overview query. Then you follow the track that matches the result. In addition, all KQL queries are in this article, placed directly at the step where you use them.

How to use this guide for performance analyse

This guide follows a fixed route. Therefore, the quick start below works for every investigation, whatever the complaint.

Quick start for your performance investigation

  1. First, fill in the header lines (see Preparation).
  2. Next, run OV-2 and choose your track with the decision table in Step 1.
  3. Then follow the track. Each query has the same structure: Question (what do you want to know), the query itself, Reading (how to interpret the output) and Next (which query follows).
  4. Finally, support every conclusion with MOM-1 or MOM-2 and record it as described in Reporting and re-measuring.

Query index: all KQL queries for API-performance

Each query has a code. Moreover, the prefix tells you which part of this article it is in (OV = Step 1, API = Track A, BEV = Track B, CODE = Track C, LOCK = Track D, MOM = Track E). As a result, you can find it quickly, because each code appears again further on as a subheading, with the query below it.

CodeFound inAnswers the questionEvent IDCode in earlier analyses
OV-1Step 1What telemetry is coming in?allQ1
OV-2Step 1Which APIs cost the most time and SQL?RT0008Q2, A7
API-1Track AWhat did each call of one API look like?RT0008Q3
API-2Track AIs the API structurally too slow?RT0008A1
API-3Track AIs it the workload or the busyness?RT0008A2
API-4Track ADoes the integration call again while BC is still processing?RT0008A3
API-5Track AHow does an API behave that does work well?RT0008A4

Query index for freezes, code, locks and moments in API-performance

The remaining queries belong to Tracks B through E.

CodeFound inAnswers the questionEvent IDCode in earlier analyses
BEV-1Track BWhen did the whole environment freeze?RT0005Q6
BEV-2Track BDo the freezes follow the working day?RT0005A5
BEV-3Track BDoes an integration send many calls at once?RT0008A6
CODE-1Track COn which line of AL code is time lost?RT0005, RT0018A8
CODE-2Track CWhich background tasks run too long?RT0018A9
LOCK-1Track DDoes a specific process fail, or is it just slow?RT0012, RT0030Q7
LOCK-2Track DWho had to wait for a lock?RT0012A10
LOCK-3Track DOn which table, and who held the lock?RT0013new
LOCK-4Track DHow much load does one extension cause?variousA11
LOCK-5Track DAre there platform or permission errors?RT0030A12
MOM-1Track EWhat happened around one point in time?variousQ4
MOM-2Track EWhat happened during each slow call?variousQ5

The last column is mainly useful if you put an older analysis document next to this guide. In new reports, however, you only use the new codes. The query codes are kept from the original guide so they match across languages (BEV = freeze, MOM = moment).

Preparation: measuring performance in Application Insights

Before you run the first query, you arrange four things: access, the header lines, the time zone and the event IDs.

Access to the Business Central performance telemetry

First, open the Application Insights resource in Azure to which the customer’s BC environment sends telemetry. You can find which resource that is in the BC admin center for the environment (Application Insights connection string). Next, go to Logs and set the time filter to Set in query. In addition, all BC telemetry is in the traces table; the details are in customDimensions.

This is how we can measure Business Central API-performance.

Header lines for every performance query

Every query in this article starts with the same let lines. Therefore, you only replace the values between < > and the lines marked // ADJUST:

let tenant = "<aadTenantId>";      // the customer's tenant ID
let envName = "<environment name>"; // for example Production
let period = 8d;                   // analysis period, at least one working week

You can find the tenant ID, for example, in the BC admin center or in any trace record (customDimensions.aadTenantId). If the resource is used by several environments, also filter on environmentName.

Time zone when measuring Business Central performance

All timestamps are UTC. For reports, therefore, convert with datetime_utc_to_local(timestamp, “Europe/Amsterdam”) (or your own time zone). However, if a timestamp comes from an integration’s log, first check whether that log uses UTC or local time. A difference of one or two hours (winter/summer) is, after all, the most common mistake.

Event IDs for Business Central performance

Event IDWhat it isKey fieldsUsed in
RT0008Web service call (API, OData, SOAP) completedendpoint, httpMethod, httpStatusCode, serverExecutionTime, sqlExecutes, sqlRowsReadStep 1, Track A, BEV-3
RT0005SQL query above the time thresholdexecutionTime, alObjectName, clientType, alStackTraceTrack B, CODE-1, MOM
RT0018AL method above the time thresholdexecutionTime, alObjectName, alMethod, clientType, alStackTraceCODE-1, CODE-2, MOM
RT0012Lock timeout: a session gave up waitingalObjectName, clientType, snapshotId, alStackTraceLOCK-1, LOCK-2
RT0013Lock snapshot at a lock timeoutsnapshotId, sqlTableName, sqlLockRequestMode, sqlLockRequestStatusLOCK-3
RT0030Error message shown to the useralErrorMessage, failureReason, alObjectNameLOCK-1, LOCK-5

Converting values. Everything in customDimensions is text. Therefore, convert it before you calculate: totimespan() for duration (divide by 1s or 1ms for a number), toint()/tolong() for counters and tostring() for filtering and grouping.

Client types (clientType): WebServiceClient = APIs and integrations, Background = job queue, WebClient = users in the browser.

The fixed order for analyzing performance

The order is fixed. You work like a funnel, from broad to narrow, and as a result the outcome of each query provides the filter for the next one (an endpoint, a point in time, an object or a snapshotId).

Five layers in the analysis of API-performance

LayerQuestionQueriesDelivers
1. OverviewWhere is the load?OV-2A list of suspect endpoints
2. SymptomHow often, when, how bad?API-1 to API-5, BEV-1 to BEV-3Structural or incidental; does it depend on busyness?
3. CauseIs it doing too much work, or is it waiting?CODE-1, CODE-2, LOCK-1 to LOCK-5Object, method, line or table
4. EvidenceDoes the explanation hold at a concrete moment?MOM-1, MOM-2Timeline per incident
5. Re-measurementDoes the fix help?The same query againBefore and after figures

Work or waiting: the key question for performance

The key question in layer 3 is therefore: work or waiting? You can read this from two RT0008 figures, namely the duration and the number of SQL statements (sqlExecutes):

What you seeMeaningGo to
Long duration and many SQL statementsThe call itself does too much work, often an N+1 pattern (a separate query per record)Track C
Long duration, normal number of SQL statementsThe call is waiting for something elseTrack E, then B or D
Same number of statements, slower during the dayThe work is the same, the environment is busyTrack B
Short duration, but errorsFunctional problem, not performanceTrack D

Roadmap for Business Central performance

Next, the roadmap below shows which query you run after which outcome. In addition, the bottom lines in each track tell you where to go next.

roadmap · step 1, five tracks, evidence

[Insert image: business-central-performance-roadmap.png] — alt text: Roadmap for Business Central performance analysis: from overview through five tracks to evidence and re-measurement

Step 1: overview of Business Central performance per endpoint

Start every investigation with OV-2. This query shows, for each endpoint, how many calls, how much server time and how much SQL work it costs. Then you use that to choose the track.

OV-1: exploring the telemetry for Business Central performance

Question: what telemetry is coming in, and how much? Use this query, for example, to check whether the connection to Application Insights works and which event IDs occur. For analysis, however, it is too broad.

let tenant = "<aadTenantId>";
let envName = "<environment name>";
let period = 8d;
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.environmentName == envName
| summarize events = count() by eventId = tostring(customDimensions.eventId)
| order by events desc

Reading: if RT0008 or RT0005 is missing completely, the telemetry is not set up correctly or the period is too short.

This is how we can measure Business Central API-performance.

OV-2: load per endpoint and the impact on Business Central performance

Question: which APIs cost the most time and SQL work?

let tenant = "<aadTenantId>";
let envName = "<environment name>";
let period = 8d;
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.environmentName == envName
| where customDimensions.eventId == "RT0008"
| extend endpoint = tostring(customDimensions.endpoint),
    method = tostring(customDimensions.httpMethod),
    dur_s = totimespan(customDimensions.serverExecutionTime) / 1s,
    sqlExec = tolong(customDimensions.sqlExecutes),
    rowsRead = tolong(customDimensions.sqlRowsRead)
| summarize calls = count(),
    totalServerMin = round(sum(dur_s) / 60, 1),
    avg_s = round(avg(dur_s), 2),
    p95_s = round(percentile(dur_s, 95), 2),
    max_s = round(max(dur_s), 1),
    avgSqlExec = round(avg(sqlExec), 0),
    avgRowsRead = round(avg(rowsRead), 0)
    by endpoint, method   // trend: add , day = startofday(timestamp)
| order by totalServerMin desc

Reading:

ColumnWhat to look forSignal
callsHow often the endpoint is calledThousands per day = high base load, even if each call is fast
totalServerMinTotal server time of the endpointAt the top = largest load on the environment
p95_s, max_sWorst durationp95 above ~5 s or max above ~30 s is noticed by users and integrations
avgSqlExecSQL statements per callThousands per call = almost certainly an N+1 pattern
avgRowsReadRows read per callRows divided by statements ≈ 1 = one query per record

Choosing the right track for Business Central performance

After OV-2, you therefore choose the next track based on the outcome:

What OV-2 showsGo to
One endpoint with high p95_s or max_sTrack A, start with API-1
One endpoint with very many calls or high totalServerMinTrack B (BEV-1) and Track C (CODE-1)
Complaint “everything is slow” without a clear endpointTrack B, start with BEV-1
Complaint about one moment (“at 10:38 the integration failed”)Track E, start with MOM-1
Error messages or stuck postingsTrack D, start with LOCK-1

Track A: slow APIs and Business Central performance

In this track, you determine how often one API is too slow. In addition, you establish whether this is structural, and whether it is caused by the workload or by busyness. Therefore, fill in the endpoint from OV-2 at let ep in every query.

API-1: Business Central performance per individual call

Question: what did each call to this endpoint look like?

let tenant = "<aadTenantId>";
let period = 8d;
let ep = "<endpoint>"; // ADJUST, for example /salesOrders
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0008"
| where tostring(customDimensions.endpoint) has ep
| extend endpoint = tostring(customDimensions.endpoint),
    dur = totimespan(customDimensions.serverExecutionTime),
    status = tostring(customDimensions.httpStatusCode),
    sqlExec = toint(customDimensions.sqlExecutes)
| project timestamp, endpoint, status, dur, sqlExec
| order by dur desc

Reading: first, compare sqlExec of the slow calls at the top with that of the fast calls at the bottom. In addition, look at status. A successful call (2xx) of 60 s often means that the integration had already given up.

Next: if slow calls have much higher sqlExec, go to API-2 and then to CODE-1. If, however, slow calls have a normal sqlExec, the call was waiting. In that case, go to MOM-2.

API-2: daily trend of Business Central performance

Question: is the API structurally too slow, or only now and then?

let tenant = "<aadTenantId>";
let period = 8d;
let ep = "<endpoint>"; // ADJUST
let limitSec = 30;     // ADJUST: the integration's timeout in seconds
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0008"
| where tostring(customDimensions.endpoint) has ep
| extend dur_s = totimespan(customDimensions.serverExecutionTime) / 1s,
    sqlExec = toint(customDimensions.sqlExecutes)
| summarize calls = count(),
    overLimit = countif(dur_s > limitSec),
    pctOverLimit = round(100.0 * countif(dur_s > limitSec) / count(), 0),
    median_s = round(percentile(dur_s, 50), 1),
    p95_s = round(percentile(dur_s, 95), 1),
    max_s = round(max(dur_s), 1),
    medianSqlExec = percentile(sqlExec, 50)
    by day = startofday(timestamp)   // remove for the total
| order by day asc

Reading: if median_s is above the integration’s timeout, the majority of calls fail, so not just the outliers. Example from an earlier analysis: a shipping API with a median of 39 s, 66% of calls above 30 s and 11,000–22,000 SQL statements per call.

Next: if you see many statements per call, go to CODE-1 for the line in the code. If you also want to know whether busyness plays a part, go to API-3.

This is how we can measure Business Central API-performance.

API-3: work or busyness? Business Central performance per hour

Question: is the duration caused only by the amount of work, or also by how busy the environment is? To find out, the query divides the duration by the number of statements, so that you get milliseconds per SQL statement.

let tenant = "<aadTenantId>";
let period = 8d;
let ep = "<endpoint>"; // ADJUST
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0008"
| where tostring(customDimensions.endpoint) has ep
| extend dur_ms = totimespan(customDimensions.serverExecutionTime) / 1ms,
    sqlExec = toint(customDimensions.sqlExecutes),
    localHour = datetime_part("hour", datetime_utc_to_local(timestamp, "Europe/Amsterdam"))
| where sqlExec > 0
| extend msPerSql = dur_ms / sqlExec
| summarize calls = count(),
    avgMsPerSql = round(avg(msPerSql), 2),
    avgDur_s = round(avg(dur_ms) / 1000, 1),
    avgSqlExec = round(avg(sqlExec), 0)
    by localHour
| order by localHour asc

Reading: an even avgMsPerSql throughout the day means pure work. A higher value during the day, on the other hand, means that the database is busy at that time. Example: ~1.5 ms per statement early in the morning versus ~2.5–3 ms during the day.

Next: if the value rises during the day, go to Track B (who is making the environment busy?).

This is how we can measure Business Central API-performance.

API-4: integration retries that hurt Business Central performance

Question: does the integration start a new call while BC is still processing the previous one? After all, that doubles the load.

let tenant = "<aadTenantId>";
let period = 8d;
let ep = "<endpoint>"; // ADJUST
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0008"
| where tostring(customDimensions.endpoint) has ep
| extend dur = totimespan(customDimensions.serverExecutionTime),
    sqlExec = toint(customDimensions.sqlExecutes)
| extend callStart = timestamp - dur, callEnd = timestamp
| order by callStart asc
| extend prevEnd = prev(callEnd), prevSqlExec = prev(sqlExec)
| extend gapSincePrevEnd = callStart - prevEnd,
    sameDataset = sqlExec == prevSqlExec,
    startedBeforePrevEnded = callStart < prevEnd
| where gapSincePrevEnd < 5m
| project callStart, dur, sqlExec, gapSincePrevEnd, sameDataset, startedBeforePrevEnded

Reading: gapSincePrevEnd is the time between the end of the previous call and the start of the next one. Furthermore, sameDataset = true probably means the same request again, and startedBeforePrevEnded = true means overlapping calls. Example: an integration that requested the same dataset again every 1–3 minutes.

Next: if the retries are confirmed, discuss with the integration owner a longer timeout, no new call while the previous one is running, or smaller batches.

API-5: comparing Business Central performance with a healthy API

Question: is the problem specific to this API, or does it apply to the whole environment? Therefore, run this query for an API that does work well.

let tenant = "<aadTenantId>";
let period = 8d;
let ep = "<endpoint>"; // ADJUST
let calls = traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0008"
| where tostring(customDimensions.endpoint) has ep
| extend dur_s = totimespan(customDimensions.serverExecutionTime) / 1s,
    sqlExec = toint(customDimensions.sqlExecutes),
    status = tostring(customDimensions.httpStatusCode);
calls
| summarize calls = count(),
    over30s = countif(dur_s > 30),
    over5s = countif(dur_s > 5),
    non2xx = countif(status !startswith "2"),
    median_s = round(percentile(dur_s, 50), 2),
    p95_s = round(percentile(dur_s, 95), 2),
    max_s = round(max(dur_s), 2),
    medianSqlExec = percentile(sqlExec, 50)
// outliers: replace the last block with
// calls | where dur_s > 5 | project timestamp, dur_s, sqlExec, status | order by dur_s desc

Reading: no calls above 30 s and a low median mean that the API is healthy. Outliers with a normal sqlExec, on the other hand, are waiting time, not work.

Next: if you have found outliers, go to MOM-2 to see what they were waiting for.

This is how we can measure Business Central API-performance.

Track B: freezes that stall Business Central performance

In this track, you look for moments when many sessions get stuck at the same time. In addition, you find out who was active at those moments.

BEV-1: detecting freezes in Business Central performance

Question: when do three or more slow SQL statements (> 3 s) end in the same second? That is, after all, the sign that they were waiting for something together.

let tenant = "<aadTenantId>";
let period = 8d;
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0005"
| extend exec = totimespan(customDimensions.executionTime)
| where exec > 3s
| summarize events = count(),
    objs = make_set(tostring(customDimensions.alObjectName)),
    clientTypes = make_set(tostring(customDimensions.clientType)),
    minExec = min(exec), maxExec = max(exec)
    by sec = bin(timestamp, 1s)
| where events >= 3
| order by minExec desc

Reading:

  • events: the number of slow statements in that second.
  • minExec: how long everything stood still at least. The worst moments are therefore at the top.
  • objs: which AL objects were involved. If one object keeps coming back, it is consequently your main suspect.
  • clientTypes: who was affected (APIs, job queue, users).

Note: the query counts events, not sessions. Three times the same API in one second are therefore usually three simultaneous requests from that API.

Next: first, take the three worst points in time to MOM-1. In addition, note the main suspect from objs for BEV-2.

BEV-2: freezes per day and hour in Business Central performance

Question: do the freezes follow the working day, and how often is the main suspect involved?

let tenant = "<aadTenantId>";
let period = 8d;
let suspect = "<AL object name from BEV-1>"; // ADJUST
let freezes = traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0005"
| extend exec = totimespan(customDimensions.executionTime)
| where exec > 3s
| summarize events = count(), minExec = min(exec),
    objs = make_set(tostring(customDimensions.alObjectName))
    by sec = bin(timestamp, 1s)
| where events >= 3
| extend local = datetime_utc_to_local(sec, "Europe/Amsterdam");
freezes
| summarize freezes = count(),
    atLeast10s = countif(minExec >= 10s),
    atLeast15s = countif(minExec >= 15s),
    atLeast20s = countif(minExec >= 20s),
    withSuspect = countif(set_has_element(objs, suspect))
    by day = startofday(local)
| order by day asc
// per hour: replace the last two lines with
// | summarize freezes = count() by hour = datetime_part("hour", local) | order by hour asc | render columnchart

Reading: freezes shows the number per day, with atLeast10s/15s/20s for severity. Moreover, withSuspect shows how often the main suspect was involved. Example from an earlier analysis: 375 moments in eight days, 85–119 per working day, almost none at night or at weekends; one web shop API was involved in 330 of the 375.

Next: if it follows the working day, the cause is busyness from users or integrations. In that case, go to BEV-3 and CODE-1. If, on the other hand, you see peaks at fixed times, including at night, it is probably the job queue: go to CODE-2.

BEV-3: API bursts that load Business Central performance

Question: does an integration (for example a web shop) send many calls at the same time?

let tenant = "<aadTenantId>";
let period = 8d;
let ep = "<endpoint>"; // ADJUST
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0008"
| where tostring(customDimensions.endpoint) has ep
| summarize callsInSecond = count() by sec = bin(timestamp, 1s)
| summarize secondsWithBurst = countif(callsInSecond >= 3),
    maxCallsInOneSecond = max(callsInSecond),
    totalCalls = sum(callsInSecond)
    by day = startofday(sec)
| order by day asc

Reading: high secondsWithBurst and maxCallsInOneSecond mean that the integration calls in parallel. Each individual call may well be fast, but together they put pressure on the database.

Next: therefore, discuss caching or fewer parallel calls with the integration owner. In addition, use CODE-1 to find out why each call is so heavy.

Track C: tracing Business Central performance back to the code

In this track, you find the object, the method and the line where the time goes. That is exactly what a developer needs for a fix.

CODE-1: Business Central performance per line in the call stack

Question: which AL code causes the slow SQL (RT0005) and the slow methods (RT0018)? To find out, the query takes the top line of the call stack (topFrame) and groups on it.

let tenant = "<aadTenantId>";
let period = 8d;
let client = "WebServiceClient"; // or "Background" (job queue) or "WebClient" (users)
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId in ("RT0018","RT0005")
| where customDimensions.clientType == client
| extend eventId = tostring(customDimensions.eventId),
    obj = tostring(customDimensions.alObjectName),
    exec_s = totimespan(customDimensions.executionTime) / 1s,
    stack = tostring(customDimensions.alStackTrace)
| extend topFrame = trim(@"\s+", tostring(split(tostring(split(stack, "AL CallStack:")[-1]), " - ")[0]))
| summarize events = count(),
    avg_s = round(avg(exec_s), 1),
    max_s = round(max(exec_s), 1)
    by eventId, obj, topFrame
| order by events desc

Reading:

  • The code with the most slow events is at the top; moreover, it is often just one or two lines.
  • topFrame shows the object, trigger or procedure and line number (for example OnOpenPage line 33). Therefore, pass this on to the developer word for word.
  • RT0018 with a high max_s is a method that is slow as a whole (for example PDF generation). RT0005 with many events, on the other hand, is a query that is slow very often, usually inside a loop.

With many statements per call (OV-2, API-2), the top line is usually a FindSet or Get inside a loop: the N+1 pattern. The solution is therefore in the code (filtering, SetLoadFields, a query object, fewer records per call), not in the infrastructure.

Next: once you have found the line, pass it on to the developer. If you also want to prove that this code coincides with freezes, run MOM-1 on a point in time from BEV-1.

This is how we can measure Business Central API-performance.

CODE-2: long job queue transactions

Question: which background tasks run for a long time? A long transaction holds locks, so that others have to wait.

let tenant = "<aadTenantId>";
let period = 8d;
let prefix = "<custom object prefix>"; // ADJUST, or remove the startswith line
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0018"
| where customDimensions.clientType == "Background"
| extend obj = tostring(customDimensions.alObjectName),
    method = tostring(customDimensions.alMethod),
    exec_s = totimespan(customDimensions.executionTime) / 1s
| where obj startswith prefix
| summarize runsOver10s = countif(exec_s > 10),
    runsOver30s = countif(exec_s > 30),
    max_s = round(max(exec_s), 1),
    avg_s = round(avg(exec_s), 1)
    by obj, method
| order by max_s desc

Reading: look mainly at max_s and runsOver30s per object and method. Example from an earlier analysis: a warehouse shipment job of up to 104 s and a pick job of up to 68 s.

Next: a job that runs longer than the lock timeout (~30 s) is a candidate cause of lock timeouts for others. Therefore, check with LOCK-2 and LOCK-3 whether there are lock timeouts on the same tables.

Track D: locks, error messages and performance

In this track, you determine who is blocking whom and on which table. Moreover, you see which errors users or integrations are getting.

LOCK-1: errors and lock timeouts per process in Business Central

Question: are there lock timeouts (RT0012) or error messages (RT0030) in the process that people are complaining about?

let tenant = "<aadTenantId>";
let period = 8d;
let process = "<object or process>"; // ADJUST, for example "Sales Return"
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId in ("RT0012","RT0030")
| where tostring(customDimensions.alStackTrace) has process
    or tostring(customDimensions.alObjectName) has process
| project timestamp, eventId = tostring(customDimensions.eventId),
    obj = tostring(customDimensions.alObjectName),
    err = tostring(customDimensions.alErrorMessage),
    stack = tostring(customDimensions.alStackTrace)

Reading: no rows means that the process does not fail, but is only slow. If there are rows, read err and stack.

Next: without rows, you go back to Track A or B. With RT0012 you then go to LOCK-2, and with RT0030 to LOCK-5.

LOCK-2: all lock timeouts affecting Business Central performance

Question: which sessions gave up waiting for a lock?

let tenant = "<aadTenantId>";
let period = 8d;
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0012"
| extend obj = tostring(customDimensions.alObjectName),
    clientType = tostring(customDimensions.clientType),
    stack = tostring(customDimensions.alStackTrace),
    snapshotId = tostring(customDimensions.snapshotId)
| project timestamp, obj, clientType, snapshotId, stack
| order by timestamp desc

Reading: obj and stack belong to the session that had to wait (the victim), so not to the cause. If the same object keeps coming back, there is moreover a recurring conflict there.

Next: take the snapshotId to LOCK-3 so that you can find the cause.

LOCK-3: lock snapshot, who blocks whom in Business Central performance

Question: on which table was the conflict, and which session held the lock? For every lock timeout, BC writes lock snapshots (RT0013) with the same snapshotId.

let tenant = "<aadTenantId>";
let period = 8d;
let snap = "<snapshotId from LOCK-2>"; // ADJUST
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0013"
| where tostring(customDimensions.snapshotId) == snap
| project timestamp,
    tableName = tostring(customDimensions.sqlTableName),
    mode = tostring(customDimensions.sqlLockRequestMode),
    status = tostring(customDimensions.sqlLockRequestStatus),
    obj = tostring(customDimensions.alObjectName),
    clientType = tostring(customDimensions.clientType),
    stack = tostring(customDimensions.alStackTrace)

This query is new and has not yet been run on an environment. Therefore, check the first result.

Reading: status = GRANT is the session that holds the lock (the cause), whereas WAIT is the session that is waiting. In addition, tableName and mode (for example X = exclusive, U = update) show where the conflict is.

Next: if the cause is a job, go to CODE-2 for the run time. If, on the other hand, the cause is an extension, go to LOCK-4.

LOCK-4: impact of an extension on Business Central performance

Question: how much slow SQL, slow methods, lock timeouts and errors come from one app?

let tenant = "<aadTenantId>";
let period = 8d;
let appPrefix = "<object prefix of the app>"; // ADJUST
let appName = "<extension name>";             // ADJUST
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId in ("RT0005","RT0012","RT0018","RT0030")
| extend stack = tostring(customDimensions.alStackTrace)
| where stack has appPrefix or tostring(customDimensions.extensionName) startswith appName
| extend eventId = tostring(customDimensions.eventId),
    clientType = tostring(customDimensions.clientType),
    exec_s = totimespan(customDimensions.executionTime) / 1s
| summarize events = count(),
    max_s = round(max(exec_s), 1),
    clientTypes = make_set(clientType)
    by eventId

Reading: look at events and max_s per event ID, and also at clientTypes to see where the app runs. An app that runs on every change through a global trigger (such as OnDatabaseModify) shows up in all client types. Example from an earlier analysis: a third-party compliance app with lock waits of up to 30 s and a lock timeout during posting.

Next: then report it with these figures to the app vendor.

LOCK-5: error and platform messages around Business Central performance

Question: are there messages from the Microsoft platform (database connection, resources rebalanced) or missing permissions?

let tenant = "<aadTenantId>";
let period = 8d;
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId == "RT0030"
| extend err = tostring(customDimensions.alErrorMessage),
    reason = tostring(customDimensions.failureReason),
    obj = tostring(customDimensions.alObjectName)
| where err has_any ("databaseverbinding", "opnieuw zijn afgestemd", "machtigingen")
// messages are in the user's language (these are the Dutch texts); adjust them, or remove this line for all error messages
| summarize occurrences = count(), firstSeen = min(timestamp), lastSeen = max(timestamp)
    by reason, obj, err
| order by occurrences desc

Reading: look at firstSeen, lastSeen and occurrences. A platform message at a single moment explains an incident at that moment, but not a structural problem.

Next: record a platform message as an external cause for that point in time, and if necessary open a ticket with Microsoft. For a permission error, on the other hand, you adjust the permission set.

Track E: Business Central performance at a specific moment

In this track, you put one moment or one slow call next to everything that happened at the same time. This is therefore the evidence behind every conclusion.

MOM-1: context around a point in time in Business Central performance

Question: what happened in the minutes around a complaint, a timeout or a freeze from BEV-1?

let tenant = "<aadTenantId>";
let t = datetime(<yyyy-mm-ddThh:mm:ssZ>); // ADJUST: point in time in UTC
let windowSize = 1m;
traces
| where timestamp between ((t - windowSize) .. (t + windowSize))
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId in ("RT0005","RT0012","RT0013","RT0018","RT0008")
| project timestamp, eventId = tostring(customDimensions.eventId), message,
    obj = tostring(customDimensions.alObjectName),
    clientType = tostring(customDimensions.clientType),
    dur = tostring(customDimensions.executionTime),
    snapshotId = tostring(customDimensions.snapshotId),
    stack = tostring(customDimensions.alStackTrace)
| order by timestamp asc

Reading: read the rows in chronological order. Then use this table:

What you seeMeaningNext
Many RT0005 from different objects ending at the same timeThe environment frozeFind who had been busy for longer; Track B
A long RT0018 from a job (Background) that started just beforeThat job probably held locksCODE-2, LOCK-3
RT0012 or RT0013 in the windowLock conflictLOCK-3 with the snapshotId
Only the RT0008 of the complaint, nothing elseThe call itself did too much workCODE-1

MOM-2: Business Central performance per slow call in context

Question: the same as MOM-1, but automatically for all slow calls of one API. First, the query calculates the start of each call. Then it looks for all slow SQL, slow methods and locks from 2 minutes before the start until 10 seconds after the end.

let tenant = "<aadTenantId>";
let period = 8d;
let ep = "<endpoint>"; // ADJUST
let threshold = 5s;    // ADJUST
let slow = traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant and customDimensions.eventId == "RT0008"
| where tostring(customDimensions.endpoint) has ep
| extend dur = totimespan(customDimensions.serverExecutionTime)
| where dur > threshold
| project callEnd = timestamp, callStart = timestamp - dur, dur, k = 1;
traces
| where timestamp > ago(period)
| where customDimensions.aadTenantId == tenant
| where customDimensions.eventId in ("RT0005","RT0012","RT0013","RT0018")
| extend k = 1
| join kind=inner slow on k
| where timestamp between ((callStart - 2m) .. (callEnd + 10s))
| project callEnd, dur, timestamp, eventId = tostring(customDimensions.eventId),
    obj = tostring(customDimensions.alObjectName),
    exec = tostring(customDimensions.executionTime),
    clientType = tostring(customDimensions.clientType),
    stack = tostring(customDimensions.alStackTrace)
| order by callEnd asc, timestamp asc

Reading: look at the rows per callEnd. If every slow call shows different objects from different client types, the call froze along with the rest of the environment. In that case, the API itself is therefore not the cause. If, on the other hand, you keep seeing the same object, that is the blocking party.

Next: if the call froze along with the rest, go to Track B. If there is always the same blocker, go to Track C or D.

Rules of thumb and pitfalls for Business Central performance

Finally, a few rules of thumb and pitfalls help you read the results correctly.

Rules of thumb for reading Business Central performance

MeasurementNormalWatch outProblem
API duration, median< 1–2 s2–10 s> 30 s (many integrations then time out)
SQL statements per API calltens to a few hundred~1,000> 5,000: almost certainly N+1
ms per SQL statement (API-3)~1–2 ms2–3 ms during the dayrises sharply with busyness
Freezes per working day (BEV-2)a fewdozens> 50, or moments ≥ 10 s
Job queue transaction (CODE-2)< 10 s10–30 s> 30 s: causes lock timeouts for others

These are, however, limits based on experience from earlier analyses, not Microsoft standards. Therefore, always compare with a quiet moment or with a well-performing API in the same environment (API-5).

Pitfalls when investigating Business Central performance

  • Forgetting UTC. A timestamp from an integration’s log without conversion will consequently miss the incident.
  • Events are not sessions. Three RT0005 events in one second can, after all, be three requests from the same API.
  • The victim is not the cause. RT0012 shows the waiting session; the cause, by contrast, only appears with LOCK-3.
  • Only slow things are logged. RT0005 and RT0018 only appear above a time threshold. “No events” therefore does not mean “no work”: so also look at sqlExecutes in RT0008.
  • Starting too broad. OV-1 without a summary returns tens of thousands of rows. Therefore, start with OV-2.
  • Too short a period. One day misses the weekly pattern. Therefore, take at least eight days.
  • Leaving example values in place. Endpoints, object names and prefixes differ per environment; so fill them in again.
  • Conclusion without evidence. Link every claim to a query and a point in time (MOM-1 or MOM-2), because otherwise it cannot be repeated.
  • Customer data in shared documents. Put tenant IDs, customer names and endpoints only in the customer report, so not in this guide or in general knowledge documents.

Reporting and re-measuring Business Central performance

Each finding in a customer report consists of three parts: the claim, the figure and the query code that produces the figure. In addition, after a fix you run exactly the same query over a comparable period, and then you put the figures side by side.

Method for a Business Central performance report

  1. First, for each query you run, record the period, the filters you filled in and the main result.
  2. Then write one sentence with a number per finding, for example “55 of 83 calls took longer than 30 s”.
  3. Next, put the findings in a table according to the template below.
  4. In addition, agree on an owner per finding: own customization (developer), integration owner, app vendor, Microsoft (platform) or administration (permissions).
  5. Finally, after the fix, run the same query over an equally long period and preferably on the same weekdays. In short, report before and after.

Customer report template for Business Central performance

FindingFigure before fixFigure after fixQuery codeFix owner
<API> structurally times out<x of y calls > 30 s, median> API-2 
<API> does too much SQL work per call<statements per call> OV-2, API-2 
Environment freezes during office hours<moments per working day, number ≥ 10 s> BEV-1, BEV-2 
<job> holds locks for a long time<max run time in s> CODE-2, LOCK-3 

Example: anonymized analysis of Business Central performance

The example below comes from an earlier analysis over eight days.

FindingFigureQuery codeFix owner
Shipping API structurally times out66% of calls > 30 s, median 39 sAPI-1, API-2Customization
Shipping API is an N+1 pattern11,000–22,000 SQL statements per callOV-2, API-2Customization
Shipping API is slower during the day for the same work~1.5 ms per statement early, ~2.5–3 ms during the dayAPI-3Consequence of busyness
Logistics integration requests again while BC is still processingThe same dataset every 1–3 minAPI-4Integration owner
Returns API works well; outliers are waiting timeMedian 1.1 s, p95 3.0 s, no calls > 30 sAPI-5, MOM-2—

Example: environment findings and Business Central performance

In the same analysis, moreover, the following findings about the whole environment emerged.

FindingFigureQuery codeFix owner
Environment freezes regularly375 moments, of which 66 ≥ 10 sBEV-1, BEV-2See below
Web shop API is almost always involved in a freezeIn 330 of 375 momentsBEV-2, BEV-3Web shop and customization
Long job queue transactionsUp to 104 sCODE-2Customization
Third-party app runs on every changeLock wait up to 30 s, one lock timeoutLOCK-4App vendor
One-off platform message about the database connectionOne momentLOCK-5Microsoft

SEO settings for WordPress (do not publish; fill in the SEO block below the post)

FieldValue
Slugbusiness-central-performance-analysis-kql
Focus keyphraseBusiness Central performance
SEO titleHow to analyze Business Central performance with KQL: guide
Meta description (146 characters, 21 words)Analyze Business Central performance with Application Insights and KQL: a step-by-step guide with ready-to-use queries and how to read the output.
Roadmap alt textRoadmap for Business Central performance analysis: from overview through five tracks to evidence and re-measurement

Last but not least, do you want to know more about Business Central telemetry, click here. Wil je contact met mij opnemen, klik dan hier.

0 Shares:
You May Also Like