Kingbase Banner

Database Diagnostics: Isolate Latency & Locks Safely

Precision tools arranged on linen for technical diagnostics

Prerequisites and Safety Boundaries

Before initiating any diagnostic procedure on a production database, you must establish a clear boundary between investigation and operational disruption. The goal is to isolate the root cause of latency or high CPU usage without triggering cascading failures or exhausting disk space with diagnostic artifacts.

This tutorial focuses on KingbaseES V9 and later, which introduced specific architectural improvements for session tracking. Earlier versions of KingbaseES recorded wait events in sys_stat_activity as instantaneous snapshots. This approach often failed to capture cumulative contention during intermittent spikes. KingbaseES V9 addressed this limitation by introducing the Kingbase Session History (KSH) feature, allowing for cumulative wait event analysis.

Environment Constraints and Privileges

Ensure the following conditions are met before proceeding:

  • Version Requirement: Confirm the database engine is KingbaseES V9 or higher. The KSH and KWR features are not available in previous versions.
  • Privilege Level: You require superuser or administrative privileges to install plugins and generate system-wide reports.
  • Storage Availability: Ensure sufficient disk space exists for the diagnostic repository. KWR snapshots and KSH history tables can grow significantly under high-concurrency workloads.
  • Maintenance Window: While the procedures below are non-disruptive, schedule the cleanup phase during a low-traffic period to minimize any residual overhead from diagnostic queries.

Plugin Installation

KingbaseES uses a plugin-based architecture for advanced diagnostics. You must verify that the following components are installed and enabled:

  1. sys_kwr: The Kingbase Workload Repository component. It captures snapshots of database time composition, OS environment, and TOP SQL.
  2. sys_ksh: The Kingbase Session History plugin. It tracks cumulative session wait events.

If these plugins are not present, the diagnostic workflow will fail. Consult the specific installation guide for your KingbaseES version to load these shared libraries.

Isolating the Bottleneck Layer: OS vs. DB vs. App

Latency spikes often stem from layers outside the database engine. Jumping straight into SQL profiling can waste time if the bottleneck is network-related or application-side logic. Use a layered isolation approach to confirm the database is the primary suspect.

Distinguishing Application Delays from Engine Contention

Application-level latency typically manifests as client-side waits. The database engine may be idle, waiting for the application to send the next request. In contrast, database engine contention occurs when the server is actively processing but blocked by resource limits or locks.

Use the following criteria to differentiate the source:

  • Application-Level Wait: The database shows low CPU usage and low active session counts, but response times are high. This suggests network latency, application-side locking, or slow client processing.
  • Database-Level Contention: The database shows high CPU usage, high active session counts, or significant wait times on internal resources (latches, buffer locks).

OS-Level Verification

Before invoking database-specific tools, verify the operating system state. High CPU usage in the database process might be caused by OS-level paging or I/O starvation.

Execute standard OS monitoring commands to check resource utilization:

  • CPU and Memory: Use top or htop to identify if the database process is consuming excessive CPU or if the system is swapping memory to disk.
  • Disk I/O: Use iostat -x 1 to check for disk saturation. High %util or await times indicate storage bottlenecks that will impact database performance regardless of SQL optimization.
  • Network: Use netstat or ss to check for connection spikes or packet drops that might cause application-level timeouts.

If the OS metrics are healthy, proceed to database-specific diagnostics.

Capturing the Baseline: Generating KWR Snapshots

Once the database is identified as the likely source of latency, capture a holistic snapshot of the workload. The Kingbase Workload Repository (KWR) provides a structured view of database time composition, wait events, and TOP SQL.

Procedure for KWR Snapshot Generation

  1. Initialize the Repository: Ensure the sys_kwr plugin is active.
  2. Generate a Baseline Snapshot: Capture the state before the incident worsens or before applying a fix.
  3. Generate an Incident Snapshot: Capture the state during the latency spike.

The exact commands to generate snapshots depend on the specific KingbaseES version and configuration. Typically, this involves calling a procedure to create a snapshot ID.

-- Example: Generate a snapshot
-- Note: Verify the exact procedure name in your KingbaseES documentation.
SELECT sys_kwr.generate_snapshot();

Analyzing the KWR Report

After capturing two snapshots (baseline and incident), generate the comparison report. The KWR report highlights:

  • OS Environment: Changes in CPU, memory, or I/O metrics between snapshots.
  • Database Time Composition: The percentage of time spent on CPU, I/O, or waiting. A high "Wait" percentage indicates resource contention.
  • Wait Events: Specific events where sessions are blocked.
  • TOP SQL: The SQL statements consuming the most resources.

This report provides the first layer of evidence for root cause analysis.

Drilling Down: Analyzing Cumulative Wait Events with KSH

While KWR provides a high-level view, it may not capture the duration of specific session waits accurately if the snapshot interval is too long. KingbaseES V9 introduced the Kingbase Session History (KSH) to address this. KSH tracks cumulative wait events per session, allowing you to see exactly how long a session waited for a specific resource.

Using the sys_ksh Plugin

The sys_ksh plugin provides detailed session history. Use it to analyze cumulative wait events.

  1. Enable KSH Collection: Ensure the KSH plugin is enabled and collecting data.
  2. Query KSH Reports: Use the provided functions to view session history.
-- Example: View KSH report
-- Note: Verify the exact function name in your KingbaseES documentation.
SELECT sys_ksh.report();

Interpreting Cumulative Waits

KSH data allows you to distinguish between:

  • Short, Frequent Waits: These may indicate latch contention or high concurrency on a specific resource.
  • Long, Continuous Waits: These often indicate lock conflicts, slow I/O, or network issues affecting a specific session.

Compare the KSH data with the KWR report. If KWR shows high "Wait" time and KSH shows specific sessions waiting for "Lock" or "Buffer" events, you have isolated the bottleneck to logical or physical resource contention.

Interpreting the Data: From Metrics to Root Cause

With KWR and KSH data in hand, you must interpret the metrics to identify the specific root cause. Ambiguity in data interpretation can lead to incorrect optimizations.

Identifying TOP SQL Bottlenecks

The KWR report lists TOP SQL statements. Look for:

  • High Execution Count: Queries running frequently, consuming CPU.
  • High Total Time: Queries running infrequently but taking a long time, consuming I/O or locks.
  • Plan Changes: If the execution plan for a TOP SQL statement has changed between the baseline and incident snapshots, this is a strong indicator of a performance regression.

Analyzing Wait Events

Correlate wait events with specific SQL statements.

  • Lock Waits: If sessions are waiting for "Lock" events, identify the blocked and blocking sessions. Use system views to find the SQL statement holding the lock.
  • I/O Waits: If sessions are waiting for "I/O" events, check the disk subsystem and the specific tables being accessed.
  • Buffer Cache Misses: High buffer cache miss rates indicate that queries are reading data not currently in memory. This suggests a need for query optimization or increasing shared memory.

Validating the Root Cause

Before applying a fix, validate that the identified SQL or resource is indeed the cause.

  1. Reproduce the Issue: If possible, reproduce the workload in a test environment.
  2. Monitor Metrics: Apply the fix (e.g., add an index, tune a parameter) and monitor the KWR/KSH metrics to confirm improvement.
  3. Check for Side Effects: Ensure the fix does not introduce new bottlenecks, such as increased lock contention or excessive memory usage.

Verification and Safe Rollback Procedures

Diagnostics create artifacts that can degrade performance if left in place. After identifying the root cause and applying a fix, you must clean up diagnostic data to restore the database to its original state.

Cleaning Up KWR Snapshots

KWR snapshots accumulate over time. Leaving old snapshots can clutter the repository and impact query performance on system views.

  1. Delete Old Snapshots: Remove snapshots that are no longer needed for analysis.
  2. Reset Statistics: If diagnostic queries reset statistics, re-run the statistics collection process to ensure accurate query planning.
-- Example: Delete a snapshot
-- Note: Verify the exact procedure name in your KingbaseES documentation.
SELECT sys_kwr.delete_snapshot(snapshot_id);

Cleaning Up KSH Data

KSH history tables can grow large. Ensure you remove the history data after analysis is complete.

  1. Truncate or Drop KSH Tables: Remove the session history data.
  2. Disable KSH Collection: If KSH was enabled for diagnostic purposes only, disable it to prevent future overhead.
-- Example: Disable KSH
-- Note: Verify the exact procedure name in your KingbaseES documentation.
-- This may involve altering a configuration parameter or calling a disable function.

Final Verification

  1. Check Disk Space: Ensure diagnostic logs and temporary tables have been removed.
  2. Monitor Performance: Verify that the database performance has returned to baseline levels.
  3. Document Findings: Record the root cause and the steps taken to resolve it for future reference.

FAQ

How can we minimize production impact while collecting sufficient diagnostic data for root cause analysis?

Use non-intrusive tools like KWR and KSH that collect data asynchronously or with minimal overhead. Avoid running heavy ad-hoc SQL scans or stopping the database. Ensure sufficient disk space is available to prevent storage-related bottlenecks during collection.

What are the trade-offs between real-time monitoring and post-mortem log analysis for intermittent latency issues?

Real-time monitoring provides immediate visibility but may miss short-lived spikes if the sampling interval is too long. Post-mortem analysis using KWR and KSH provides detailed, cumulative data but requires the incident to have occurred. For intermittent issues, a combination of both is ideal: use real-time alerts to trigger KWR/KSH snapshot collection at the moment of the spike.

Which diagnostic parameters are critical for distinguishing lock management issues from resource contention?

Focus on wait events. "Lock" events indicate logical lock conflicts. "I/O" or "Buffer" events indicate resource contention. KSH cumulative wait times help distinguish between short, frequent locks and long, blocking locks.

How can we validate that diagnostic scripts have been fully cleaned up to prevent residual performance overhead?

Verify that KWR snapshots and KSH history tables have been deleted or truncated. Check that diagnostic plugins are disabled if they were only needed for the investigation. Monitor system views to ensure no lingering diagnostic queries are running.


💡 More Resources

If you would like to dive deeper into KingbaseES and its application practices across various industries, we have compiled the following official resources to help you get started quickly and develop and operate with efficiency:

  • Kingbase Community: A one-stop interactive platform for technical exchanges, Q&A, and experience sharing—join forces with fellow DBAs and developers.
  • Kingbase Solutions: One-stop full-stack database migration and cloud-native solutions, supporting smooth migration of multi-source heterogeneous data, ensuring high availability, real-time integration, and sustained high performance.
  • Kingbase Case Studies: Real-world user scenarios and implementation outcomes, showcasing KingbaseES’s outstanding capabilities in high availability, high performance, and IT adaptation.
  • Kingbase Documentation: Authoritative and comprehensive product manuals and technical guides, covering the entire lifecycle from installation and deployment to development, programming, and operations management.
  • Free Download: Get the latest installation packages, drivers, tools, and patches, supporting multiple platforms and domestic chip architectures.
  • Digital Construction Encyclopedia: Covers digital strategy planning, data integration, metrics management, database visualization applications, and more to empower enterprise digital transformation.

Open Source Resources:

Welcome to explore the resources above and begin your Kingbase journey!