# system_health - Astar RPC Method

Returns the health status of the Astar node, including peer count, sync state, and whether the node expects to have peers.

> **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration.

## When to Use This Method

`system_health` is essential for multi-chain dApp developers, DeFi builders, and teams leveraging Polkadot + Ethereum ecosystems:

- **Health Checks** - Monitor node availability and readiness before routing traffic on Astar
- **Load Balancing** - Route requests only to healthy, fully synced nodes for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos
- **Sync Status** - Verify a node is caught up before trusting its state queries
- **Infrastructure Alerts** - Trigger alerts when peers drop or sync stalls

## Best Practices

- Call at application startup before processing any transactions
- If `isSyncing` is `true`, delay all transaction operations until it returns `false`
- Low `peers` count may indicate network connectivity issues
- Combine with `system_chain` and `system_version` for a complete node health check

## Request Parameters

This method accepts no parameters.

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "system_health",
  "params": [],
  "id": 1
}
```

## Response Fields

- `peers` (`Number, required`): Number of connected peers
- `isSyncing` (`Boolean, required`): true if the node is still syncing with the network
- `shouldHavePeers` (`Boolean, required`): true if the node is expected to have peers (false for local dev chains)

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "peers": 42,
    "isSyncing": false,
    "shouldHavePeers": true
  }
}
```

## Error Responses

### Error Response

- Code: `-32603`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "Internal error"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Rust

```bash
curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "system_health",
    "params": [],
    "id": 1
  }'
```

```javascript
import { ApiPromise, WsProvider } from '@polkadot/api';

const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY');
const api = await ApiPromise.create({ provider });

const health = await api.rpc.system.health();
console.log('Peers:', health.peers.toNumber());
console.log('Is syncing:', health.isSyncing.isTrue);
console.log('Should have peers:', health.shouldHavePeers.isTrue);

const isHealthy = !health.isSyncing.isTrue && health.peers.toNumber() > 0;
console.log('Node healthy:', isHealthy);

await api.disconnect();
```

```python
import requests

def get_health():
    url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY'

    payload = {
        'jsonrpc': '2.0',
        'method': 'system_health',
        'params': [],
        'id': 1
    }

    response = requests.post(url, json=payload)
    result = response.json()

    if 'error' in result:
        raise Exception(f"RPC Error: {result['error']}")

    return result['result']

health = get_health()
print(f"Peers: {health['peers']}")
print(f"Syncing: {health['isSyncing']}")
print(f"Should have peers: {health['shouldHavePeers']}")

is_healthy = not health['isSyncing'] and health['peers'] > 0
print(f"Node healthy: {is_healthy}")
```

```rust
use subxt::{OnlineClient, PolkadotConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api = OnlineClient::<PolkadotConfig>::from_url(
        "wss://api-astar.n.dwellir.com/YOUR_API_KEY"
    ).await?;

    let health = api.rpc()
        .system_health()
        .await?;

    println!("Peers: {}", health.peers);
    println!("Is syncing: {}", health.is_syncing);
    println!("Should have peers: {}", health.should_have_peers);

    let is_healthy = !health.is_syncing && health.peers > 0;
    println!("Node healthy: {}", is_healthy);

    Ok(())
}
```

## Common Use Cases

### 1. Readiness Probe for Kubernetes

Use as a health check endpoint for container orchestration on Astar:

```javascript
import express from 'express';
import { ApiPromise, WsProvider } from '@polkadot/api';

const app = express();
const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY');
const api = await ApiPromise.create({ provider });

app.get('/healthz', async (req, res) => {
  try {
    const health = await api.rpc.system.health();
    const isReady = !health.isSyncing.isTrue && health.peers.toNumber() > 0;

    if (isReady) {
      res.status(200).json({ status: 'healthy', peers: health.peers.toNumber() });
    } else {
      res.status(503).json({
        status: 'not ready',
        syncing: health.isSyncing.isTrue,
        peers: health.peers.toNumber()
      });
    }
  } catch (error) {
    res.status(503).json({ status: 'unreachable', error: error.message });
  }
});
```

### 2. Multi-Node Load Balancer

Route traffic only to healthy Astar nodes:

```javascript
async function selectHealthyNode(endpoints) {
  const results = await Promise.allSettled(
    endpoints.map(async (endpoint) => {
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          method: 'system_health',
          params: [],
          id: 1
        })
      });

      const { result } = await response.json();
      return { endpoint, ...result };
    })
  );

  const healthy = results
    .filter(r => r.status === 'fulfilled' && !r.value.isSyncing)
    .map(r => r.value)
    .sort((a, b) => b.peers - a.peers);

  return healthy.length > 0 ? healthy[0].endpoint : null;
}
```

### 3. Continuous Health Monitor

Periodically check node health and alert on degradation:

```python
import requests
import time

def monitor_health(endpoint, interval=30, min_peers=5):
    while True:
        try:
            payload = {
                'jsonrpc': '2.0',
                'method': 'system_health',
                'params': [],
                'id': 1
            }

            response = requests.post(endpoint, json=payload, timeout=5)
            health = response.json()['result']

            peers = health['peers']
            syncing = health['isSyncing']

            if syncing:
                print(f'WARNING: Node is syncing (peers: {peers})')
            elif peers < min_peers:
                print(f'WARNING: Low peer count: {peers}')
            else:
                print(f'OK: peers={peers}, syncing={syncing}')

        except Exception as e:
            print(f'ERROR: Node unreachable - {e}')

        time.sleep(interval)

monitor_health('https://api-astar.n.dwellir.com/YOUR_API_KEY')
```

## Related Methods

- [`system_version`](https://www.dwellir.com/docs/astar/system_version) - Get node software version
- [`system_chain`](https://www.dwellir.com/docs/astar/system_chain) - Get chain name
- `system_syncState` - Get detailed sync progress
- `system_peers` - Get detailed peer information
