The XRPL Communication Layer - Architecture & Design Philosophy | XRPL APIs & Integration | XRP Academy - XRP Academy
Skip to main content
intermediate50 min

The XRPL Communication Layer - Architecture & Design Philosophy

Learning Objectives

Explain the dual-protocol architecture (WebSocket vs JSON-RPC) and articulate when to use each

Identify the three types of XRPL servers (rippled, Clio, public) and match them to appropriate use cases

Describe the API versioning system and correctly specify versions in requests

Evaluate the trade-offs between running your own node versus using public infrastructure

Map specific integration requirements to optimal server/protocol combinations

Here's a secret about the XRPL API: it wasn't designed by a product team with a whiteboard full of user stories. It evolved organically from the internal communication protocol that rippled nodes use to talk to each other. What you're accessing when you connect to a rippled server is essentially the same interface that validators use during consensus—exposed to the outside world with some access controls.

This origin explains both the API's power and its quirks. On one hand, you get direct access to everything happening on the network—no abstraction layer hiding important details. On the other hand, the API reflects the concerns of distributed systems engineering (Byzantine fault tolerance, state synchronization, network partitioning) rather than the concerns of application developers (ease of use, clear error messages, intuitive workflows).

Why This Matters for Your Integration:

The XRPL API gives you more power than most blockchain APIs—but that power comes with responsibility. You're not calling a sanitized REST endpoint that returns exactly what you need in a friendly format. You're communicating with a distributed ledger node that's simultaneously participating in consensus, relaying transactions, serving historical data, and managing peer connections.

  • Choose the right protocol for your use case (and know when to use both)
  • Select appropriate server infrastructure (public vs private, rippled vs Clio)
  • Interpret responses correctly (including the subtle differences between server states)
  • Build resilient applications that handle the realities of distributed systems

Let's examine each layer of this communication architecture.


The XRPL API is available through two distinct protocols:

WebSocket: A persistent, bidirectional connection where the server can push data to your application without being asked.

JSON-RPC over HTTP: A stateless request/response protocol where your application sends a request and waits for a response.

Most web APIs pick one protocol and stick with it. The XRPL offers both because they serve fundamentally different interaction patterns:

WEBSOCKET                          JSON-RPC (HTTP)
─────────────────────────────────────────────────────────
Connection    Persistent           Per-request
Direction     Bidirectional        Request → Response
Server Push   Yes (subscriptions)  No
State         Connection maintains Request is stateless
              context              
Overhead      Low after connect    Higher (new connection
                                   per request)
Complexity    Higher (connection   Lower (standard HTTP)
              management)
Best For      Real-time apps,      Simple queries, 
              monitoring,          serverless functions,
              high-frequency       occasional lookups

The Key Insight: These aren't competing options—they're complementary tools. Production applications often use both: WebSocket for real-time features (payment confirmations, price feeds) and JSON-RPC for simple queries (balance checks, transaction lookups).

WebSocket connections to rippled use the standard WebSocket protocol (RFC 6455) with JSON-formatted messages. The connection URL typically looks like:

wss://s1.ripple.com:51233    (Public mainnet)
wss://s.altnet.rippletest.net:51233    (Testnet)
ws://localhost:6006    (Local node, development)

Connection Lifecycle:

  1. HANDSHAKE

  2. COMMUNICATION

  3. MAINTENANCE

  4. TERMINATION

What WebSocket Enables:

The killer feature of WebSocket is subscriptions—the ability to receive updates pushed from the server without polling. You can subscribe to:

  • Ledger stream: Notification every time a new ledger closes (every 3-5 seconds)
  • Transactions stream: All validated transactions network-wide
  • Transactions_proposed stream: Transactions entering the proposed set (before validation)
  • Account transactions: Transactions affecting specific accounts
  • Order book changes: Updates to specific trading pairs
  • Validations stream: Validation messages from validators

Without subscriptions, monitoring for incoming payments would require polling every few seconds—wasteful and still potentially missing transactions between polls. With subscriptions, the server tells you immediately when something relevant happens.

WebSocket Complexity:

The power of WebSocket comes with implementation complexity:

CHALLENGES YOU'LL FACE:

- Connections drop (network issues, server restarts)
- Need reconnection logic with backoff
- Must re-subscribe after reconnection
- State synchronization after gaps

- Responses may arrive out of order
- Must correlate responses to requests (using id field)
- Subscription updates interleaved with responses
- Need message routing logic

- Connections consume server resources
- Public servers may disconnect idle connections
- Must implement keepalive/heartbeat
- Memory management for subscription buffers

When WebSocket Is the Right Choice:

✅ Your application needs real-time updates (payment monitoring, trading)
✅ You're making many requests per second (high-frequency operations)
✅ You need server-pushed notifications (alerts, confirmations)
✅ You're building a long-running service (not serverless)

JSON-RPC over HTTP follows a simple request/response pattern. Send an HTTP POST with a JSON body, receive a JSON response.

Request Format:

{
  "method": "account_info",
  "params": [{
    "account": "rN7n3473SaZBCG4dFL83w7a1RXtXtbk2D9",
    "ledger_index": "validated",
    "api_version": 2
  }]
}

Response Format:

{
  "result": {
    "account_data": {
      "Account": "rN7n3473SaZBCG4dFL83w7a1RXtXtbk2D9",
      "Balance": "123456789",
      "Sequence": 42,
      ...
    },
    "ledger_index": 87654321,
    "status": "success",
    "validated": true
  }
}

JSON-RPC Simplicity:

The beauty of JSON-RPC is its simplicity:

ADVANTAGES:

- No connection to maintain
- Each request is independent
- Perfect for serverless (Lambda, Cloud Functions)

- HTTP status codes for transport errors
- JSON error field for API errors
- No complex state machine

- Any HTTP client works
- curl, Postman, requests, fetch
- No WebSocket library needed

- Request/response pairs easy to log
- No interleaved messages
- Tools like Postman work directly

JSON-RPC Limitations:

LIMITATIONS:

- Can't receive server-pushed updates
- Must poll for changes (inefficient)
- Potential to miss events between polls

- New TCP connection per request (unless HTTP keep-alive)
- SSL handshake overhead
- Not suitable for high-frequency operations

- Can't build real-time UIs efficiently
- Payment confirmation requires polling
- Order book monitoring impractical

When JSON-RPC Is the Right Choice:

✅ Simple, infrequent queries (balance checks, transaction lookups)
✅ Serverless functions (Lambda, Cloud Functions—no persistent connections)
✅ Scripts and CLI tools (simple request/response)
✅ Applications without real-time requirements
✅ Initial prototyping (easier to debug)

Production applications typically use both protocols strategically:

HYBRID ARCHITECTURE EXAMPLE:

┌─────────────────────────────────────────────────────┐
│              Your Application                        │
├─────────────────────────────────────────────────────┤
│                                                      │
│  ┌─────────────────┐    ┌─────────────────────────┐ │
│  │ Payment Monitor │    │ Balance Lookup Service  │ │
│  │   (WebSocket)   │    │      (JSON-RPC)         │ │
│  │                 │    │                         │ │
│  │ • Subscribe to  │    │ • On-demand queries     │ │
│  │   account txns  │    │ • Serverless compatible │ │
│  │ • Real-time     │    │ • Simple implementation │ │
│  │   confirmations │    │                         │ │
│  └────────┬────────┘    └───────────┬─────────────┘ │
│           │                         │               │
└───────────┼─────────────────────────┼───────────────┘
            │                         │
     (WebSocket)                (HTTP POST)
            │                         │
┌───────────▼─────────────────────────▼───────────────┐
│                  rippled Server                      │
└─────────────────────────────────────────────────────┘

Decision Framework:

USE WEBSOCKET WHEN:
□ Need real-time updates
□ High request frequency (>1 per second sustained)
□ Building long-running services
□ Subscription-based features required

USE JSON-RPC WHEN:
□ Occasional queries
□ Serverless deployment
□ Simple scripts or tools
□ No real-time requirements

USE BOTH WHEN:
□ Real-time monitoring + on-demand queries
□ Microservice architecture
□ Different components have different needs

rippled (pronounced "ripple-dee") is the core server software that participates in the XRP Ledger network. Every node running rippled:

  • Maintains a copy of the ledger
  • Validates and processes transactions
  • Participates in consensus (if configured as validator)
  • Serves API requests
  • Relays messages to other nodes

rippled Modes:

  • Stores complete ledger history

  • Can answer any historical query

  • Requires significant storage (TB+)

  • Slowest to sync initially

  • Stores recent ledger history

  • Configurable retention period

  • Balanced storage/capability

  • Most common configuration

  • Participates in consensus

  • Usually doesn't serve public API

  • Critical network infrastructure

  • Special security requirements

  • Historical queries only

  • Being replaced by Clio

  • May encounter in older documentation

When to Run Your Own rippled:

Running your own node provides:

No rate limits: Query as frequently as needed
Privacy: Your queries aren't visible to third parties
Reliability: Not dependent on external infrastructure
Admin access: Methods not available on public servers
Customization: Configure for your specific needs

The costs:

Infrastructure: Server with 8GB+ RAM, fast SSD, good bandwidth
Maintenance: Updates, monitoring, troubleshooting
Sync time: Initial sync takes hours to days
Expertise: Need to understand node operations

Recommendation:

  • Development/testing: Use public servers or testnet
  • Production with moderate load: Start with public, add own node as needed
  • High-frequency or sensitive operations: Run your own node
  • Enterprise/institutional: Definitely run your own (multiple for HA)

Clio is a specialized XRP Ledger server optimized for API serving and historical queries. Unlike rippled, Clio doesn't participate in consensus—it connects to rippled nodes to get data, then stores and indexes it for efficient retrieval.

Clio vs rippled:

                        rippled              Clio
────────────────────────────────────────────────────
Primary Purpose    Network participation   API serving
Consensus          Yes (if validator)      No
Historical Data    Limited by config       Optimized storage
Query Performance  Good                    Better for history
Resource Usage     Higher                  Lower for API-only
Real-time Data     Direct from network     Via rippled connection
Admin Methods      Yes                     No

When to Use Clio:

  • Historical transaction queries

  • Account history with pagination

  • Ledger data analysis

  • High-volume read operations

  • Submit transactions (forwards to rippled)

  • Participate in consensus

  • Provide admin methods

  • Guarantee real-time data (slight delay possible)

Public Clio Servers:

Ripple operates Clio servers alongside rippled for their public infrastructure. When you connect to s1.ripple.com or s2.ripple.com, load balancers may route your request to either rippled or Clio depending on the operation.

Several organizations provide public XRPL API access:

Ripple-Operated Servers:

MAINNET:
wss://s1.ripple.com:51233     (Primary cluster)
wss://s2.ripple.com:51233     (Secondary cluster)
https://s1.ripple.com:51234    (JSON-RPC)
https://s2.ripple.com:51234    (JSON-RPC)

TESTNET:
wss://s.altnet.rippletest.net:51233
https://s.altnet.rippletest.net:51234 

DEVNET:
wss://s.devnet.rippletest.net:51233
https://s.devnet.rippletest.net:51234 

Community Infrastructure:

  • Community-operated

  • Geographic distribution

  • Alternative to Ripple servers

  • Some provide public endpoints

  • Check current availability

Public Server Limitations:

  • Requests per minute capped

  • Varies by server and load

  • No guaranteed SLA

  • Best effort, not guaranteed

  • May have maintenance windows

  • No compensation for downtime

  • Public methods only

  • No admin access

  • May restrict some operations

  • Your queries visible to operator

  • IP address logged

  • Query patterns observable

The Critical Question: When Are Public Servers Appropriate?

ACCEPTABLE FOR:
✓ Development and testing
✓ Low-volume production (<100 requests/minute)
✓ Non-critical applications
✓ Getting started quickly
✓ Backup/failover (secondary to own node)

NOT RECOMMENDED FOR:
✗ High-frequency trading
✗ Financial operations requiring SLA
✗ Privacy-sensitive queries
✗ Applications requiring admin methods
✗ Mission-critical production systems

Here's how to choose your infrastructure based on requirements:

REQUIREMENT                    → RECOMMENDATION
───────────────────────────────────────────────────
Just learning/prototyping      → Public servers
Low volume, non-critical       → Public servers
Need admin methods             → Own rippled
High query volume              → Own rippled or Clio
Historical data focus          → Clio
Real-time + history            → rippled + Clio
Privacy requirements           → Own infrastructure
99.9%+ uptime SLA needed       → Own infrastructure (redundant)
Enterprise/institutional       → Own infrastructure (multiple nodes)

The XRPL API has evolved significantly since launch. To maintain backward compatibility while enabling improvements, rippled introduced API versioning. Currently, two versions are actively supported:

  • **API Version 1:** Original API format (legacy)
  • **API Version 2:** Improved format with better consistency and additional features

Key Differences:

CHANGE                           V1              V2
─────────────────────────────────────────────────────────
Amount format (XRP)             String drops    String drops (same)
Amount format (issued)          Object          Object (same)
Transaction hash field          "hash"          "hash" (normalized)
Ledger index field             Various          "ledger_index" (consistent)
Account sequence               Various          "sequence" (consistent)
Error format                   Varies           Standardized
Default for new connections    If unspecified   Recommended

In WebSocket/JSON-RPC Requests:

{
  "command": "account_info",
  "account": "rN7n3473SaZBCG4dFL83w7a1RXtXtbk2D9",
  "api_version": 2
}

In Client Libraries:

// xrpl.js - API version configured at client level
const client = new xrpl.Client('wss://s1.ripple.com:51233', {
  // xrpl.js uses API v2 by default in recent versions
})
# xrpl-py - API version in request
from xrpl.clients import JsonRpcClient
from xrpl.models.requests import AccountInfo

Use API Version 2 for all new development.

  • More consistent field naming

  • Better error messages

  • Actively maintained

  • Will receive future improvements

  • Maintaining legacy code that depends on V1 behavior

  • Specific V1 quirk is required (rare)

Checking Server Version Support:

// Request
{
  "command": "server_info"
}

// Response includes
{
  "result": {
    "info": {
      "build_version": "1.12.0",
      "complete_ledgers": "32570-87654321",
      "network_id": 0,
      ...
    }
  }
}

The build_version indicates server capabilities. All modern rippled versions support both API versions.


Understanding connection URLs helps troubleshoot connectivity issues:

wss://s1.ripple.com:51233
│     │            │
│     │            └── Port (WebSocket secure: 51233, JSON-RPC: 51234)
│     └── Host (server address)
└── Protocol (wss = WebSocket Secure, https = JSON-RPC secure)

COMMON PORTS:
51233    WebSocket (WSS)
51234    JSON-RPC (HTTPS)
6006     WebSocket (WS, local/development)
5005     JSON-RPC (HTTP, local/development)

Essential Connection Parameters:

// Connection with configuration
const client = new xrpl.Client('wss://s1.ripple.com:51233', {
  timeout: 10000,           // Request timeout (ms)
  connectionTimeout: 5000,  // Connection timeout (ms)
  // Additional options vary by library
})

Timeout Considerations:

TIMEOUT SCENARIOS:

- Fails on slow networks
- Fails during high load
- Causes unnecessary retries

- Poor user experience
- Resource waste on hung connections
- Delayed error detection

- Connection timeout: 5-10 seconds
- Request timeout: 10-20 seconds
- Adjust based on operation (historical queries may need longer)
  • Any production environment
  • Any sensitive data
  • Mainnet connections
  • Local development (localhost)
  • Isolated test environments
  • Performance testing where TLS overhead matters

Certificate Validation:

// Most libraries validate certificates by default
// Only disable for development/testing, NEVER production

// Node.js environment variable (development only!)
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'  // DANGEROUS

The dual-protocol design works: WebSocket for real-time, JSON-RPC for simplicity—each serves its purpose well

Public infrastructure is reliable for development: Ripple's servers have good uptime for non-critical use

API versioning enables evolution: Breaking changes can be introduced without breaking existing integrations

Clio improves historical queries: Specialized infrastructure genuinely performs better for its use case

⚠️ Public server long-term availability: No contractual guarantee; terms could change

⚠️ Rate limit specifics: Not well-documented; varies by load and server

⚠️ Clio feature parity: Not all rippled features available; edge cases may require rippled

⚠️ Future API versions: V3 could introduce changes; migration effort unknown

🔴 Depending solely on public infrastructure for production: Single point of failure with no SLA

🔴 Ignoring API version specifications: Default behavior may change; explicit versioning prevents surprises

🔴 Using insecure connections for production: Man-in-the-middle attacks, credential exposure

🔴 Not implementing reconnection logic: WebSocket connections will drop; applications must handle this

The XRPL communication layer is well-designed for its purpose—direct access to a distributed ledger. It's more complex than typical web APIs because you're interacting with distributed systems infrastructure, not a curated developer experience. Understanding this architecture is essential before writing integration code; skipping this foundation leads to brittle applications that fail in production.


Assignment: Design a server infrastructure strategy for a hypothetical payment processor.

Scenario:

  • Accept XRP payments for an e-commerce platform
  • Process 10,000+ payments per day (peak: 50/minute)
  • Require 99.9% uptime
  • Need real-time payment confirmations (<30 seconds)
  • Store transaction history for 2 years

Requirements:

Part 1: Infrastructure Design (40%)

  • Which server type(s) you'll use (rippled, Clio, public)
  • How many instances and their configuration
  • Geographic distribution (if any)
  • Connection protocols for each component

Justify each choice with specific reasoning.

Part 2: Protocol Selection (30%)

  • Which protocol (WebSocket, JSON-RPC, or both)

  • Why that protocol fits the component's needs

  • Connection management approach

  • Payment monitoring service

  • Balance lookup API

  • Transaction history queries

  • Admin/operations tools

Part 3: Failure Modes & Mitigation (30%)

  • What happens if primary server fails?

  • What happens if network connection drops?

  • What happens if server is overloaded?

  • How do you detect and recover from each scenario?

  • Technical accuracy (correct understanding of server types and protocols): 30%

  • Appropriate matching of requirements to solutions: 30%

  • Completeness of failure mode analysis: 25%

  • Quality of justifications: 15%

Time Investment: 2-3 hours

Submission Format: Document (PDF or Markdown) with diagrams for architecture

Value: This exercise forces you to think through real infrastructure decisions before you're under pressure to make them in production. Your strategy document becomes a reference for actual implementation.


1. Protocol Selection (Tests Understanding):

A serverless function (AWS Lambda) needs to check an XRP account balance when triggered by an HTTP request. Which protocol should it use?

A) WebSocket, because it's faster
B) JSON-RPC over HTTP, because Lambda functions are stateless and short-lived
C) Either works equally well
D) Neither—serverless can't connect to XRPL

Correct Answer: B

Explanation: Lambda functions are stateless and short-lived—they spin up, execute, and terminate. WebSocket's persistent connection model doesn't fit this pattern; you'd waste time establishing connections that are immediately closed. JSON-RPC's request/response model is perfect: send request, get response, function terminates. Option A is wrong because WebSocket connection establishment overhead makes it slower for single requests. Option C is wrong because WebSocket is poorly suited to serverless. Option D is wrong—serverless can absolutely make HTTP requests.


2. Server Type Analysis (Tests Critical Thinking):

A trading application needs real-time order book updates AND the ability to query 6-month transaction history. Which infrastructure setup is most appropriate?

A) Single rippled node with full history
B) Public servers only (s1.ripple.com)
C) rippled for real-time + Clio for historical queries
D) Clio only

Correct Answer: C

Explanation: This application has two distinct requirements: real-time data (order book updates) and historical queries (6-month history). rippled excels at real-time data but storing full history requires significant resources. Clio is optimized for historical queries but relies on rippled for real-time data. The combination gives best performance for both needs. Option A works but is resource-intensive. Option B risks rate limits and has no SLA for a trading app. Option D can't efficiently provide real-time order book streaming.


3. API Version Question (Tests Knowledge):

What happens if you don't specify api_version in your XRPL API requests?

A) Request fails with an error
B) Server uses its default version (currently version 1 for backward compatibility)
C) Server always uses the latest version
D) Server randomly selects a version

Correct Answer: B

Explanation: For backward compatibility, servers default to API version 1 when not specified. This prevents breaking existing applications that were written before versioning existed. However, relying on this default is risky—future servers could change the default. Best practice is to explicitly specify api_version: 2 in all requests. Option A is wrong—requests work without version specified. Option C is wrong—that would break legacy applications. Option D is obviously wrong.


4. Infrastructure Decision (Tests Application):

Your startup is launching an XRP payment feature. You have limited budget and engineering resources. Current projected volume is 100 payments per day. Which infrastructure approach is most appropriate for your initial launch?

A) Run three geographically distributed rippled nodes immediately
B) Use public servers initially, with monitoring and plans to add own infrastructure if volume grows
C) Don't launch until you can run your own infrastructure
D) Use public servers permanently—they're free and reliable

Correct Answer: B

Explanation: At 100 payments/day (~0.07/minute), public server rate limits won't be an issue. Over-investing in infrastructure before product-market fit wastes resources. The pragmatic approach: launch with public servers, monitor carefully, and have a plan to add own infrastructure when either (a) volume approaches rate limits, (b) reliability becomes critical, or (c) you have resources. Option A is over-engineering for current scale. Option C delays launch unnecessarily. Option D ignores that public servers have no SLA—fine for now, risky as you grow.


5. Protocol Characteristics (Tests Comprehension):

Which statement about WebSocket connections to XRPL is FALSE?

A) WebSocket allows the server to push transaction notifications without polling
B) WebSocket connections must be actively maintained with reconnection logic
C) WebSocket is required for any interaction with the XRPL
D) WebSocket connections can subscribe to ledger and transaction streams

Correct Answer: C

Explanation: WebSocket is NOT required—JSON-RPC over HTTP provides full access to XRPL query and submission capabilities. WebSocket is only required if you need subscriptions (server-pushed updates). Options A, B, and D are all true statements about WebSocket: it enables subscriptions (A), requires reconnection handling (B), and supports various stream subscriptions (D).


For Next Lesson:
Lesson 2 dives deep into WebSocket connections—establishing them, managing their lifecycle, and implementing the reconnection patterns that production applications require. We'll write code that handles the real-world messiness of persistent connections.


End of Lesson 1

Total words: ~4,800
Estimated completion time: 50 minutes reading + 2-3 hours for deliverable


  1. Establishes mental model of XRPL communication layer before diving into code
  2. Introduces decision frameworks students will use throughout course
  3. Sets realistic expectations about infrastructure requirements
  4. Distinguishes XRP Academy from documentation (we explain "why," not just "what")
  • "I need to run my own node to use XRPL" → No, public servers work for development
  • "WebSocket is always better" → No, each protocol has appropriate use cases
  • "Public servers are production-ready" → They work but have limitations
  • "API version doesn't matter" → It does; explicit versioning is important

Why This Comes Before Code:
Students who skip architectural understanding write brittle code. They use WebSocket when JSON-RPC is simpler. They depend on public infrastructure for mission-critical apps. They don't implement reconnection logic. This lesson prevents those mistakes by building understanding first.

Lesson 2 Setup:
Now that students understand the landscape, Lesson 2 gets hands-on with WebSocket—the more complex but powerful protocol. We'll implement proper connection management, reconnection logic, and subscription handling.

Key Takeaways

1

WebSocket and JSON-RPC serve different needs:

Use WebSocket for real-time features and high-frequency operations; use JSON-RPC for simple queries and serverless deployments. Production applications often use both.

2

Server type matters for your use case:

rippled for full capabilities, Clio for optimized historical queries, public servers for development—but plan your own infrastructure for production.

3

Specify API version explicitly:

Use `api_version: 2` in all requests. Don't rely on defaults that could change.

4

Public servers have limitations:

Rate limits, no SLA, no admin access, no privacy. Acceptable for development; risky for production.

5

Infrastructure investment scales with requirements:

Start simple, but recognize when you need dedicated infrastructure—before you hit scaling problems. ---