system_health
Description#
Retrieves the health status of a Polkadot node, including peer count, synchronization status, and overall node health. This method is essential for monitoring node performance and network connectivity.
Parameters#
This method does not require any parameters.
Returns#
| Field | Type | Description |
|---|---|---|
peers | number | Number of connected peers |
isSyncing | boolean | Whether the node is currently syncing with the network |
shouldHavePeers | boolean | Whether the node should have peers (false for dev nodes) |
Request Example#
{
"jsonrpc": "2.0",
"method": "system_health",
"params": [],
"id": 1
}
Response Example#
{
"jsonrpc": "2.0",
"result": {
"peers": 25,
"isSyncing": false,
"shouldHavePeers": true
},
"id": 1
}
Code Examples#
- cURL
- Python
- JavaScript
- TypeScript (@polkadot/api)
curl https://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_health",
"params": [],
"id": 1
}'
import requests
import json
import time
def check_node_health():
url = "https://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY"
headers = {
"Content-Type": "application/json"
}
payload = {
"jsonrpc": "2.0",
"method": "system_health",
"params": [],
"id": 1
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
data = response.json()
if "error" in data:
raise Exception(f"RPC Error: {data['error']}")
return data["result"]
def monitor_health(interval_seconds=30):
"""Monitor node health continuously"""
while True:
try:
health = check_node_health()
status = "Syncing" if health["isSyncing"] else "Synced"
print(f"Node Status: {status}")
print(f"Connected Peers: {health['peers']}")
# Alert on issues
if health["peers"] == 0 and health["shouldHavePeers"]:
print("⚠️ WARNING: No peers connected!")
if health["peers"] < 3 and health["shouldHavePeers"]:
print("⚠️ WARNING: Low peer count!")
except Exception as e:
print(f"Error checking health: {e}")
time.sleep(interval_seconds)
# Single health check
health = check_node_health()
print(f"Node health: {health}")
const checkNodeHealth = async () => {
const response = await fetch('https://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'system_health',
params: [],
id: 1
})
});
const data = await response.json();
const health = data.result;
console.log('Node Health:', {
status: health.isSyncing ? 'Syncing' : 'Synced',
peers: health.peers,
healthy: health.peers > 0 && !health.isSyncing
});
return health;
};
// Monitor health periodically
const monitorHealth = async (intervalMs = 30000) => {
setInterval(async () => {
const health = await checkNodeHealth();
if (health.peers === 0 && health.shouldHavePeers) {
console.error('WARNING: No peers connected!');
}
if (health.isSyncing) {
console.log('Node is syncing...');
}
}, intervalMs);
};
import { ApiPromise, WsProvider } from '@polkadot/api';
interface NodeHealth {
peers: number;
isSyncing: boolean;
shouldHavePeers: boolean;
}
class NodeMonitor {
private api: ApiPromise;
constructor(api: ApiPromise) {
this.api = api;
}
async checkHealth(): Promise<NodeHealth> {
const health = await this.api.rpc.system.health();
return {
peers: health.peers.toNumber(),
isSyncing: health.isSyncing.isTrue,
shouldHavePeers: health.shouldHavePeers.isTrue
};
}
async getDetailedStatus() {
const [health, chain, name, version, syncState] = await Promise.all([
this.api.rpc.system.health(),
this.api.rpc.system.chain(),
this.api.rpc.system.name(),
this.api.rpc.system.version(),
this.api.rpc.system.syncState()
]);
return {
chain: chain.toString(),
nodeName: name.toString(),
nodeVersion: version.toString(),
peers: health.peers.toNumber(),
isSyncing: health.isSyncing.isTrue,
syncProgress: syncState.currentBlock.toNumber() / syncState.highestBlock.toNumber()
};
}
startMonitoring(intervalMs: number = 30000) {
setInterval(async () => {
const status = await this.getDetailedStatus();
console.log('Node Status:', status);
// Alert logic
if (status.peers === 0) {
console.error('CRITICAL: No peers connected!');
} else if (status.peers < 3) {
console.warn('Warning: Low peer count');
}
if (status.isSyncing) {
console.log(`Syncing: ${(status.syncProgress * 100).toFixed(2)}% complete`);
}
}, intervalMs);
}
}
// Usage
const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com');
const api = await ApiPromise.create({ provider });
const monitor = new NodeMonitor(api);
// Single check
const health = await monitor.checkHealth();
console.log('Health:', health);
// Start monitoring
monitor.startMonitoring(60000); // Check every minute
Health Status Interpretation#
Peer Count#
| Peers | Status | Description |
|---|---|---|
| 0 | Critical | No network connectivity |
| 1-2 | Warning | Low connectivity, may have issues |
| 3-10 | Good | Acceptable connectivity |
| 10+ | Excellent | Well connected to network |
Sync Status#
isSyncing | Meaning |
|---|---|
true | Node is downloading and processing historical blocks |
false | Node is synchronized with the network |
Should Have Peers#
shouldHavePeers | Meaning |
|---|---|
true | Normal network node, should connect to peers |
false | Development/isolated node, peer connection optional |
Use Cases#
- Monitoring Dashboards: Display node health metrics
- Alerting Systems: Trigger alerts on connectivity issues
- Load Balancers: Route traffic based on node health
- Deployment Validation: Verify node setup and connectivity
- Troubleshooting: Diagnose synchronization problems
Monitoring Best Practices#
Health Check Implementation#
class HealthChecker {
constructor(endpoint, apiKey) {
this.endpoint = endpoint;
this.apiKey = apiKey;
this.healthHistory = [];
}
async check() {
try {
const health = await this.getHealth();
this.healthHistory.push({
timestamp: Date.now(),
...health
});
// Keep last 100 checks
if (this.healthHistory.length > 100) {
this.healthHistory.shift();
}
return this.analyzeHealth(health);
} catch (error) {
return {
status: 'error',
message: error.message
};
}
}
analyzeHealth(health) {
const issues = [];
if (health.peers === 0 && health.shouldHavePeers) {
issues.push('No peer connections');
}
if (health.peers < 3 && health.shouldHavePeers) {
issues.push('Low peer count');
}
if (health.isSyncing) {
issues.push('Node syncing');
}
return {
status: issues.length === 0 ? 'healthy' : 'degraded',
issues,
metrics: health
};
}
getAveragePeers() {
if (this.healthHistory.length === 0) return 0;
const sum = this.healthHistory.reduce(
(acc, h) => acc + h.peers, 0
);
return sum / this.healthHistory.length;
}
}
Related Methods#
chain_getBlock- Check latest blockchain_getBlockHash- Get block hashesstate_getMetadata- Get runtime metadataauthor_submitExtrinsic- Submit transactions
Notes#
- Health checks should be performed regularly but not excessively
- Peer count can fluctuate normally - look for trends
- Syncing status is normal for new nodes or after downtime
- Consider multiple health checks before triggering alerts
- Different node types (validator, full, light) have different health characteristics