Tuning and resource control
Before tuning, record a fixed baseline and locate the bottleneck. Change one setting at a time, then decide whether to retain it. Memory limits are soft budgets, and agent and taosX budgets do not cover one another. Retest under similar load after changes. Meeting a budget while failing to catch up within source retention is not success.
Where to operate: task advanced options in taosExplorer, taosx.toml or agent.toml on the actual execution host; taosx run for standalone tasks.
Tuning aims to keep taosX, collection agent, and target service resource use controlled while meeting data timeliness and completeness requirements.
1. Common tuning: measure first, change one setting
Record a baseline using Logs and performance. Locate whether the limit comes from the source, network, parsing and transformation, target writes, or intentional resource restrictions. Change only one category of settings at a time, recording original values, expected improvement, and rollback conditions.
| Symptom | First action | Verification focus |
|---|---|---|
| Target write failures keep increasing | Fix connections, permissions, structures, and data errors first | Failures stop increasing and missing data is checked |
| Backlog grows despite sufficient host resources | Check target capacity, then adjust batches or concurrency supported by the connector | Processing rate, target lag, and target service resources |
| Memory keeps growing | Check data batches, queued work, source bursts, and target slowdowns | Memory stabilizes without shifting uncontrolled backlog to disk or source |
| High CPU with complex transformations | Check whether filtering, splitting, and transformation are necessary, then assess processing capacity | CPU, lag, and failure rate with the same input |
| Historical catch-up crowds out other workloads | Set a suitable budget for the actual execution process or schedule tasks in batches | Other services recover while historical tasks still finish as planned |
Batch, polling, and concurrency settings differ by connector. Do not copy one parameter set to every source. Larger queues temporarily hold more pending data but do not improve sustained target processing capacity.
First check Shared advanced field applicability to distinguish settings that can be saved from settings that actually take effect. For example, in direct source DSNs for InfluxDB and OpenTSDB, write_concurrency and batch_timeout do not control corresponding plugin output, and OpenTSDB batch_size cannot be adjusted through that entry either. A same-name control or successful save does not establish effectiveness. Even with smaller output batches, SQL Server may cache an entire SQL query result. Also control the query window and observe memory.
Before changes, use Configuration files to distinguish process budgets from task DSN parameters. CLI --jobs sets runtime threads; it is not connector workers or total task count. Agent and taosX budgets are independent. Changing one end does not mean the entire path is rate-limited.
1.1 Make a reversible adjustment
- Obtain a baseline for the same task using SQL or Grafana as described in Logs and performance, such as 10 consecutive minutes of input, writes, failures, and target lag. Note run start and load.
- If failures keep increasing, fix their causes before performance tuning. If the target is saturated, arrange target capacity or reduce input first instead of increasing concurrency and worsening congestion.
- Export the task or save process configuration, then select one identified adjustment. For example, if the current connector actually supports batch settings, adjust that setting on a test task first. Do not change collection intervals, batches, and concurrency together.
- After saving, restart the task or process as required by that setting. Repeat the same observation duration under similar load and check a real record's timestamp, value, and tags.
- Retain the new value only if processing improves, errors do not increase, and source backlog can be caught up. Otherwise restore the old value and reverify. Do not record lower CPU with no data reaching the target as successful optimization.
- Linux
- Windows
1.2 Observe process resources on Linux
In Bash on the actual taosX or agent host, use procps ps to find relevant processes and top for continuous observation. Minimal containers may lack these tools. Use the original deployment method to inspect from an environment with process visibility; do not start another business process:
ps -C taosx,taosx-agent -o pid,ppid,user,pcpu,rss,etimes,args
Output includes PID, parent PID, account, CPU percentage, RSS, elapsed seconds, and startup command. RSS is in KiB; divide by 1024 for MiB. If no process is listed, check the host, process names, and permissions first instead of interpreting usage as zero. Startup commands may contain sensitive arguments; redact them before external submission.
After obtaining a real PID, for example 1234, check direct children and observe the main process:
ps --ppid 1234 -o pid,ppid,user,pcpu,rss,etimes,args
top -d 2 -p 1234
--ppid lists direct children only, not every level. Continue checking by parent PID if connectors are deeper in the hierarchy. With no direct children, ps may show only headers and return exit code 1. This does not establish a main-process fault; assess task type and running state. top refreshes every 2 seconds; press q to exit. The PID selected with -p does not include child processes. Observe confirmed relevant PIDs separately. PIDs may change after service restarts and must be found again.
When collecting evidence in a noninteractive terminal, use batch mode to avoid waiting indefinitely for manual exit:
top -b -n 2 -d 2 -p 1234
-b uses batch output suitable for text capture, -n 2 exits after two samples, and -d 2 sets a 2-second refresh interval. Replace the PID with the actual value. Save sample times and both outputs. Compare refreshed results instead of capturing only the first screen.
ps %CPU is usually averaged over process lifetime, whereas top shows a refresh window. CPU definitions also depend on display mode, and multicore processes may exceed 100%. These values cannot be directly compared with taosX budget percentages calculated against total capacity across all CPU cores. Do not simply add process RSS values as an exact total without shared memory either. Align objects, times, and units first, then assess bottlenecks with task throughput and errors.
On Windows, use Task Manager to view CPU and memory for taosX, agent, and connector processes by PID. Match PIDs to process logs or monitoring. Use the same window for host and task monitoring, and include connector subprocesses.
1.3 MQTT and Sparkplug B message batching
Batch settings in these two entries have the same meanings. See each source page for initial form values; do not generalize them to Kafka or query sources.
| Setting | Effect on processing |
|---|---|
| In-flight batch limit | Limits batches concurrently entering processing, with a minimum of 1; reaching the limit may create upstream backlog. It is not messages per batch or disk cache capacity. |
| Batch size | Send when a batch is full; increasing it may improve throughput but also increases per-batch processing and memory load. Parsing splits, filtering, and primary-key overwrites change final row counts. |
| Batch timeout | Starts with the first message in a batch; sends when time expires even if the batch is not full. It is not the broker consumer wait timeout. |
| Write concurrency | Controls concurrent target-write tasks, not device count, topic count, or QoS. Compare lag, errors, and target load before increasing it. |
Use the baseline and rollback steps above, checking new-message lag and data that must be retained. Do not improve metrics by discarding backlog. Configure MQTT wait queues, real-time caches, and raw-data retention separately using its source page. Sparkplug B does not offer the same three switches.
2. Set process resource budgets
Use taosx.toml for service mode and agent.toml for collection agents. Configure each process independently. Default configuration directories are /etc/taos on Linux and C:\TDengine\cfg on Windows. Standalone taosx run uses its supported --resource.* options; check taosx run --help first.
Without [resource], resource control is disabled. The following memory budget values are examples, not defaults or universally recommended sizing:
[resource]
enabled = true
maxMemoryMB = 2048
maxPauseSecs = 10
This example sets a 2048 MiB soft memory budget for the process and connector subprocesses included in accounting. Exceeding it adjusts processing speed; it does not guarantee actual RSS always stays below it. Choose budgets based on total host memory, other services, and representative load.
To control network write usage, add the following to the same [resource] section:
maxWriteMBps = 20
Units use 1 MiB = 1024 × 1024 bytes and measure data payload handed to the writer, including short bursts. This does not represent all protocol traffic on the network interface. Do not append another same-name [resource] section after an existing one.
Restart the relevant process in a maintenance window after changes. Confirm in startup logs that resource limits are enabled, then repeat baseline measurements. Restoring original configuration also requires a restart. To retain the section while disabling resource control, set enabled = false.
2.1 Confirm budgets are active
First search the relevant process logs for resource memory brake armed, resource egress bucket armed, or resource cpu brake armed and check actual budgets. See Error codes and log keywords for search methods. These armed messages mean activation, not failure.
If taosX reports monitoring to taosKeeper and the resource table exists, first run DESCRIBE log.taosx_resource; in the monitoring cluster's taosExplorer Data Browser or taos CLI, then query:
SELECT _ts, taosx_id, resource_rss_bytes, resource_brake_paused,
resource_bucket_wait_ms_total, resource_brake_max_pause_total,
resource_cpu_brake_max_pause_total
FROM log.taosx_resource
WHERE taosx_id = 'taosx-host:6050' AND _ts > NOW - 15m
ORDER BY _ts DESC LIMIT 20;
Replace database and instance identifiers according to Logs and performance. If the table is missing, confirm resource control and monitoring are enabled for this process. Do not create an empty same-name table just to make the query succeed.
| Observation | Meaning and action |
|---|---|
resource_rss_bytes | RSS bytes for accounted processes; divide by 1024 × 1024 to compare with the MiB budget, not directly with a percentage |
resource_brake_paused=1 | Data processing was paused at sampling time; use multiple samples and logs to determine frequency |
Growing resource_bucket_wait_ms_total | Bandwidth throttling waits exist; compare budget and actual throughput to determine whether this is expected intentional throttling |
| Growing memory or CPU max-pause counters | Processing is allowed after the per-pause limit is reached; check whether the budget is below the normal working set or downstream has slowed. Do not immediately conclude a memory leak |
Compare increments in cumulative waits and counts within the same process run, and establish a new baseline after restart. Sampling intervals may miss brief pauses, so never sampling 1 does not prove no pause occurred. Agents do not export these metrics; use agent logs and system monitoring on agent hosts.
3. Advanced tuning: CPU and resource boundaries
Use maxCpuPercent and cpuResumePercent for CPU budgets. For example, maxCpuPercent = 50 and cpuResumePercent = 30 in the same section adjust writes above a high watermark measured against total capacity across all CPU cores, and resume below the recovery watermark. The recovery watermark must be lower than the high watermark.
maxCpuCores limits runtime thread counts; it is not a hard CPU utilization cap. If operating-system hard limits are required, set them in the deployment environment and verify task recovery and cache capacity at those limits beforehand.
Resource control has these boundaries:
- Memory is a soft budget. Each pause is limited by
maxPauseSecs; an overly low budget may repeatedly pause and release processing. - MQTT and Sparkplug B are push sources. Read-side memory pauses do not control their reception and do not guarantee a hard cap on receive memory.
- Connector buffering still requires actual process monitoring. A budget on taosX does not automatically set the same budget on an agent on another host.
- Observe taosX-Agent resource control through agent logs and system monitoring on its host. taosX-Agent does not provide an endpoint for reading
resource_*metrics.
See Resource configuration mapping for detailed defaults, environment variables, and platform restrictions. Before first use on a platform, verify with the actual distribution and task.
4. Control disk growth
Distinguish logs, raw-data retention, error archives, pending-write caches, agent persistent queues, and database backups by directory purpose. Locate the growing directory and owning task before deciding how to handle it.
Error archives support diagnosis and backups support recovery; neither replaces pending-send caches. Preserve persistent queues until delivery is confirmed and the product reclaims them normally.
Pending-rewrite caches for target writes are not automatically evicted by retention days or file count. The interface's space setting is actually a single-file rotation threshold and does not limit total directory usage. Do not rely on default settings such as 30d, 100 files, or 1GB to prevent caches filling disks. See Write error policies for full parameters and archive cleanup rules. Distinguish archives from pending-rewrite caches when checking capacity and configuring alerts.
Disk alerts must leave time for intervention and catch-up. Estimate capacity as measured hourly cache growth × permitted interruption duration, then add headroom for catch-up, logs, and error peaks. Do not estimate agent caches only from compressed target database size.
For example, if undelivered caches grow by 2 GiB/hour during an isolated drill and must cover a 6-hour interruption, caches alone need at least 12 GiB, plus new data generated during catch-up, logs, and safety headroom. This illustrates the calculation method, not a fixed connector capacity specification.
- Linux
- Windows
On the Linux host storing caches, perform read-only checks with Bash and GNU df, du, find, and awk. Replace paths with actual directories of confirmed ownership:
queue_dir='/var/lib/taos/taosx/tasks/123/-1/cache'
df -h -- "$queue_dir"
du -sh -- "$queue_dir"
find "$queue_dir" -type f -printf '%s\n' |
awk '{total_bytes += $1} END {printf "%.0f\n", total_bytes}'
df -h shows capacity, used space, available space, and utilization of the directory's filesystem; base free-space alerts on its available space. du -sh summarizes actual directory disk usage in readable units. The last command totals logical sizes of regular files in bytes, allowing growth comparisons on the same basis as the Windows example. Logical sizes differ from actual disk usage because of sparse files, filesystem allocation, and metadata; do not mix them.
For an agent persistent queue, run on the agent host and replace queue_dir with the actual persist_data_dir. Do not copy this taosX target-cache path to the agent. Repeat samples at fixed intervals and record start/end times and directories. Permission errors, rotation during scans, or ongoing writes may make results incomplete or approximate snapshots, not exact undelivered quantities. Recursive scans of large directories consume I/O; lower their frequency. None of these commands delete files.
On Windows, gather read-only statistics for a directory of confirmed ownership on the host actually storing it:
$queueDir = 'D:\taosx-cache\task-123'
Get-ChildItem -LiteralPath $queueDir -File -Recurse |
Measure-Object -Property Length -Sum
Replace $queueDir with the real cache directory. Sum is the current total file size in bytes. Repeat after a fixed interval to measure growth. Avoid frequent recursive scans for large directories. This command performs no cleanup and does not prove every byte represents undelivered business data.
5. Configure, inspect, and clean up raw-data retention
Enable raw-data retention only for connectors that support it. It adds disk and I/O load on the actual collection host and may retain sensitive business data.
For example, enable raw-data retention in MQTT task advanced options. In a source DSN, the corresponding parameters are keep_raw_data=true, keep_raw_data_dir, and keep_raw_data_days. First choose a writable directory on the collection host, then explicitly set retention, for example keep_raw_data_days=1. The directory belongs to the actual collection host, not the browser host. Restart the task after changing it.
Send an identifiable test message. Check file times and contents in the specified directory on the collection host and confirm the message is present. MQTT defaults to a rawdata subdirectory under the task and job data directories. Use actual configuration for custom paths. Inspect samples read-only and control access according to sensitive-data requirements.
List recently updated files first, then inspect a small file or stable copy. Do not open the whole retention directory or paste all contents into a ticket. Use text tools for text formats and the connector's instructions for non-text formats. taosx archive is not a universal reader for raw data files. If the test message is missing, first check the actual collection host, whether configuration was saved, and whether the task restarted, then permissions and logs.
Retention rules vary by connector. MQTT handles retention by daily files. AVEVA Historian keep_raw_data_days actually controls the count of rotated files and cannot promise a number of retained days. Do not generalize one connector's parameter meanings to others.
5.1 Inspect OPC regular point-value retention
OPC UA and OPC DA regular point-value retention files start with opc_data.dump. followed by rotation time. Contents are headerless CSV. These are not OPC point mapping CSV files or error archives; do not upload them as point lists or interpret them with taosx archive. Event subscriptions are not verified using this regular point-value format.
First check task keep_raw_data, keep_raw_data_dir, and retention values. Where legacy aliases enable, path, and keep exist, each takes precedence over its corresponding setting; do not supply conflicting pairs. Managed tasks may derive the default directory from execution context. Standalone taosx run without that context cannot merely enable retention without an actual writable path. See OPC collection and runtime parameters for parameters and activation conditions.
Each CSV record contains these fields in order:
| Position | Meaning | How to check |
|---|---|---|
| 1, 2 | Source point identifier and name | Compare the complete NodeId or DA point name and task scope; similar names do not establish the same source point. |
| 3, 4 | Start and end of this collection | For UA polling, these help inspect read-phase duration. For UA subscriptions, both are notification handling times, and their difference is not source-read duration. Neither is successful target-write time. |
| 5 | Point-value time | UA prefers the source timestamp, then falls back to server timestamp and collection host current time in that order; it is not always source event time. Displayed in the collection host's time zone; compare with source records. |
| 6, 7 | Value and output type | Check against the approved test point; interpret commas, quotes, and newlines inside strings according to CSV rules. |
| 8 | Status | UA uses status names and DA numeric quality codes; do not compare them as the same text. |
Time fields show month/day and hours/minutes/seconds, without year or time-zone offset. For cross-year, daylight-saving, or cross-host analysis, separately retain the task window, host time zone, and file origin. This column alone cannot reconstruct the full event time. To assess UA source-value freshness, also confirm the timestamp actually supplied by the source. Records using fallback times alone do not prove the source value has just updated.
- Linux
- Windows
Inspect UA regular point-value retention in Bash on the actual collection host, or an authorized stable copy. DA collection still occurs on Windows; reading a copy does not mean Linux can run the DA plugin:
raw_directory='/var/lib/taos/taosx/opc raw'
find "$raw_directory" -maxdepth 1 -type f -name 'opc_data.dump.*' -printf '%TY-%Tm-%Td %TH:%TM:%TS %s %f\n' | sort -r
raw_file=$(find "$raw_directory" -maxdepth 1 -type f -name 'opc_data.dump.*' -print -quit)
if [ -n "$raw_file" ]; then
printf 'Previewing: %s\n' "$raw_file"
head -n 6 -- "$raw_file"
else
printf 'No OPC raw files found; check the task, host and directory.\n'
fi
The file list shows modification time, bytes, and filename. The preview selects a file found in the directory, not necessarily the newest. For a specific window, identify the file in the list before inspecting it. These commands use GNU find and sort; confirm availability in minimal containers first.
In PowerShell on the actual collection host, replace the directory with the retention directory saved in the task. These commands only list files and preview the newest file's first six lines; they do not modify files:
$raw_directory = 'C:\TDengine\data\opc raw'
$raw_files = @(Get-ChildItem -LiteralPath $raw_directory -File -Filter 'opc_data.dump.*' |
Sort-Object LastWriteTime -Descending)
if ($raw_files.Count -eq 0) { throw 'No OPC raw files found; check the task, host and directory.' }
$raw_files | Select-Object -First 5 Name, Length, LastWriteTime
Get-Content -LiteralPath $raw_files[0].FullName -Encoding UTF8 -TotalCount 6
This is only a text preview; six lines do not necessarily represent six complete CSV records. Use a CSV tool on a stable copy for strings containing newlines. A file still being written may not yet show the latest data. For missing lines, first check dump channel is full, failed to write csv, path permissions, and remaining disk space. File existence does not establish complete collection or writes. Retention adds queue and disk load; it is not an optimization to reduce collection pressure. Cleanup rules do not replace disk capacity alerts.
5.2 Inspect pSpace raw-data retention
When pSpace retention is enabled, data is appended to UTF-8 TSV files on the actual reading host, named rawdata-YYYY-MM-DD.tsv. The date is the day the plugin runs, not each record's business date. The default directory is ./rawdata under the plugin working directory and is not automatically isolated by task. Use keep_raw_data_dir to specify separate controlled absolute directories for different tasks.
Enable retention and restart the original task as described above, then have the source administrator provide a known new test value. Before running the commands below, replace the directory with the task's actual retention directory. Commands list files and read the first six lines of the newest file by filename date, without deleting or modifying files. If no files exist, confirm that the task received new values, directory permissions, and the actual reading host first. Do not create empty files instead of verifying.
- Linux
- Windows
Run in Bash on the actual Linux reading host:
raw_dir='/var/lib/taosx-diagnostics/pspace-task'
find "$raw_dir" -maxdepth 1 -type f -name 'rawdata-*.tsv' -printf '%f\n' |
LC_ALL=C sort -r | head -n 5
sample_name=$(find "$raw_dir" -maxdepth 1 -type f -name 'rawdata-*.tsv' -printf '%f\n' |
LC_ALL=C sort | tail -n 1)
if [ -z "$sample_name" ]; then
printf '%s\n' '未找到 pSpace 留存文件,请检查任务和目录' >&2
exit 1
fi
head -n 6 -- "$raw_dir/$sample_name"
Run in PowerShell on the actual Windows reading host:
$rawDir = 'C:\taosx-diagnostics\pspace-task'
$rawFiles = @(Get-ChildItem -LiteralPath $rawDir -Filter 'rawdata-*.tsv' -File |
Sort-Object Name -Descending)
$rawFiles | Select-Object -First 5 Name, Length, LastWriteTime
if ($rawFiles.Count -eq 0) { throw '未找到 pSpace 留存文件,请检查任务和目录' }
Get-Content -LiteralPath $rawFiles[0].FullName -Encoding UTF8 -TotalCount 6
Headers are timestamp, tagId, name, value, and quality, separated by tabs. Check samples against actual point IDs, test times, values, and quality. Time text has no offset; also record the plugin host/JVM time zone. Active files may not have flushed all contents, and the first six lines may not include the newest value. If needed, search for approved identifiers in a controlled copy. Do not paste entire files or other tasks' data into tickets.
pSpace keep_raw_data_days does not guarantee corresponding automatic expiry cleanup. Do not copy MQTT daily-retention rules. Configure directory capacity alerts and approved retention/cleanup procedures. Raw-data retention is neither an error archive nor a database backup and does not prove complete target ingestion.
After troubleshooting, disable retention and restart the task. Confirm that no new files of this type appear. Before cleanup, save samples still needed for analysis and check file ownership, time ranges, and retention requirements. Remove only raw data files confirmed no longer needed; do not recursively clean the entire task directory. Verify actual automatic-rotation retention against file inventories, not just configuration values.
6. Change verification and rollback
Compare before and after under similar load and duration: target data completeness, lag, backlog, failure counts, and host resources. Meeting a budget while failing to catch up within source retention is not successful tuning.
If lag worsens, resource pauses persist, or target errors increase, restore the original settings and verify task and data recovery. Retain both metric sets and configuration differences for further capacity planning or support analysis.