> For the complete documentation index, see [llms.txt](https://docs.shyft.to/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.shyft.to/solana-shredstreaming/how-to-stream-with-rabbitstream.md).

# How to stream with RabbitStream

Rabbitstream Quickstart: Connecting with TypeScript and Rust

RabbitStream is designed to be a seamless, <mark style="color:yellow;">drop-in replacement</mark> for your existing Yellowstone gRPC clients, requiring only a change of endpoint URL.

{% hint style="info" %}

#### Beta-access already available for everyone with a <mark style="color:yellow;">Shyft gRPC</mark> token.

{% endhint %}

### Access and Authentication

RabbitStream requires a valid <mark style="color:yellow;">Shyft gRPC</mark> <mark style="color:yellow;">token</mark>. gRPC access is included with our *Build, Grow*, and *Accelerate* plans. Once you have your token, you can access the stream using the following regional endpoints:

| **Ams** (Amsterdam)        | `https://rabbitstream.ams.shyft.to/` |
| -------------------------- | ------------------------------------ |
| **VA** (Virginia, Ashburn) | `https://rabbitstream.va.shyft.to/`  |
| NY (New York)              | `https://rabbitstream.ny.shyft.to/`  |
| **Fra** (Frankfurt)        | `https://rabbitstream.fra.shyft.to/` |

### Connecting to RabbitStream: Client Examples

Once you have your Shyft gRPC Access Token, you can connect to Rabbitstream in the following manner:

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import "dotenv/config";

import Client, {
  CommitmentLevel,
  SubscribeRequest,
  SubscribeRequestAccountsDataSlice,
} from "@triton-one/yellowstone-grpc";

const client = new Client(
  "https://rabbitstream.ams.shyft.to/",
  process.env.X_TOKEN,
  undefined
);

const req: SubscribeRequest = {
  accounts: {},
  slots: {},
  transactions: {
    pumpFun: {
      vote: false,
      failed: false,
      signature: undefined,
      accountInclude: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"],
      accountExclude: [],
      accountRequired: [],
    },
  },
  transactionsStatus: {},
  entry: {},
  blocks: {},
  blocksMeta: {},
  accountsDataSlice: [] as SubscribeRequestAccountsDataSlice[],
  ping: undefined,
  commitment: CommitmentLevel.PROCESSED,
};

async function handleStream(client: Client, args: SubscribeRequest) {
  // Subscribe for events
  console.log(`Subscribing and starting stream...`);
  const stream = await client.subscribe();

  // Create `error` / `end` handler
  const streamClosed = new Promise<void>((resolve, reject) => {
    stream.on("error", (error) => {
      console.log("ERROR", error);
      reject(error);
      stream.end();
    });
    stream.on("end", () => {
      resolve();
    });
    stream.on("close", () => {
      resolve();
    });
  });

  // Handle updates
  stream.on("data", (data) => {
    console.log("Received data....");
    console.dir(data, { depth: null });
  });

  // Send subscribe request
  await new Promise<void>((resolve, reject) => {
    stream.write(args, (err: any) => {
      if (err === null || err === undefined) {
        resolve();
      } else {
        reject(err);
      }
    });
  }).catch((reason) => {
    console.error(reason);
    throw reason;
  });

  await streamClosed;
}

async function subscribeCommand(client: Client, args: SubscribeRequest) {
  while (true) {
    try {
      await handleStream(client, args);
    } catch (error) {
      console.error("Stream error, restarting in 1 second...", error);
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }
}

subscribeCommand(client, req);

```

{% endtab %}

{% tab title="Rust" %}

```rust
use {
    backoff::{future::retry, ExponentialBackoff},
    clap::Parser as ClapParser,
    futures::{
        future::TryFutureExt,         
        stream::StreamExt,
    },
    log::{error, info},
    std::{collections::HashMap, env, sync::Arc, time::Duration},
    tokio::sync::Mutex,
    tonic::transport::channel::ClientTlsConfig,
    yellowstone_grpc_client::{GeyserGrpcClient, Interceptor},
    yellowstone_grpc_proto::{
        geyser::SubscribeRequestFilterTransactions,
        prelude::{ CommitmentLevel, SubscribeRequest},
    },
};


type TxnFilterMap = HashMap<String, SubscribeRequestFilterTransactions>;

const PUMPFUN_AMM_PROGRAM_ID: &str = "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA";


#[derive(Debug, Clone, ClapParser)]
#[clap(author, version, about)]
struct Args {
    #[clap(short, long, help = "gRPC endpoint")]
    endpoint: String,

    #[clap(long, help = "X-Token")]
    x_token: String,
}

impl Args {
    async fn connect(&self) -> anyhow::Result<GeyserGrpcClient<impl Interceptor>> {
        GeyserGrpcClient::build_from_shared(self.endpoint.clone())?
            .x_token(Some(self.x_token.clone()))?
            .connect_timeout(Duration::from_secs(10))
            .timeout(Duration::from_secs(10))
            .tls_config(ClientTlsConfig::new().with_native_roots())?
            .max_decoding_message_size(1024 * 1024 * 1024)
            .connect()
            .await
            .map_err(Into::into)
    }

    pub fn get_txn_updates(&self) -> anyhow::Result<SubscribeRequest> {
        let mut transactions: TxnFilterMap = HashMap::new();

        transactions.insert(
            "client".to_owned(),
            SubscribeRequestFilterTransactions {
                vote: Some(false),
                failed: Some(false),
                account_include: vec![PUMPFUN_AMM_PROGRAM_ID.to_string()],
                account_exclude: vec![],
                account_required: vec![],
                signature: None,
            },
        );

        Ok(SubscribeRequest {
            accounts: HashMap::default(),
            slots: HashMap::default(),
            transactions,
            transactions_status: HashMap::default(),
            blocks: HashMap::default(),
            blocks_meta: HashMap::default(),
            entry: HashMap::default(),
            commitment: Some(CommitmentLevel::Processed as i32),
            accounts_data_slice: Vec::default(),
            ping: None,
            from_slot: None,
        })
    }
}



#[tokio::main]
async fn main() -> anyhow::Result<()> {
    env::set_var(
        env_logger::DEFAULT_FILTER_ENV,
        env::var_os(env_logger::DEFAULT_FILTER_ENV).unwrap_or_else(|| "info".into()),
    );
    env_logger::init();

    let args = Args::parse();
    let zero_attempts = Arc::new(Mutex::new(true));

    retry(ExponentialBackoff::default(), move || {
        let args = args.clone();
        let zero_attempts = Arc::clone(&zero_attempts);

        async move {
            let mut zero_attempts = zero_attempts.lock().await;
            if *zero_attempts {
                *zero_attempts = false;
            } else {
                info!("Retry to connect to the server");
            }
            drop(zero_attempts);

            let client = args.connect().await.map_err(backoff::Error::transient)?;
            info!("Connected");

            let request = args.get_txn_updates().map_err(backoff::Error::Permanent)?;

            geyser_subscribe(client, request)
                .await
                .map_err(backoff::Error::transient)?;

            Ok::<(), backoff::Error<anyhow::Error>>(())
        }
        .inspect_err(|error| error!("failed to connect: {error}"))
    })
    .await
    .map_err(Into::into)
}

async fn geyser_subscribe(
    mut client: GeyserGrpcClient<impl Interceptor>,
    request: SubscribeRequest,
) -> anyhow::Result<()> {
    let ( subscribe_tx, mut stream) = client.subscribe_with_request(Some(request)).await?;
    info!("stream opened");


    while let Some(message) = stream.next().await {
        match message {
            Ok(msg) => println!("Received Message: {:#?}", msg),
            Err(e) => error!("Failed to receive message: {e}"),
        }
    }

    info!("stream closed");
    Ok(())
}
```

{% endtab %}
{% endtabs %}

### Performance Benchmarks: The Speed Advantage

RabbitStream is ideal for applications that need <mark style="color:yellow;">low-latency transaction monitoring</mark>, such as *DeFi dashboards, arbitrage bots, or token analytics tools*. We compared the detection latency between RabbitStream and Yellowstone gRPC. All the code for this comparison tool is available on GitHub for you to try out.

<div data-full-width="false"><figure><img src="https://2394289113-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4XnSsBH76iytbI7NwX5o%2Fuploads%2F9h6lT7xICF59GNQ6hHDn%2Ftoken-2.png?alt=media&amp;token=ff47aef6-5046-47ed-a485-d8530ea58bd5" alt=""><figcaption></figcaption></figure></div>

### Closing a connection

Once connected, we can gracefully terminate a connection using the following steps:&#x20;

1. **Cancel the stream.** Tells RabbitStream directly, via HTTP/2 `RST_STREAM`, that this stream is gone.
2. **Close the channel.** Releases the underlying TCP/TLS connection to RabbitStream.

### Why the order matters

Closing the channel is a *graceful* HTTP/2 shutdown: it waits for any streams still open on that channel to finish on their own before the connection actually goes away. If the stream were still open when you closed the channel, the close would sit there waiting on it. Cancel the stream first and the close has nothing left to wait on, so the disconnect from RabbitStream completes immediately instead of stalling.y

{% tabs %}
{% tab title="TypeScript" %}

```
stream.cancel();                  // RST_STREAM — tells RabbitStream the stream is gone
(client as any)._client.close();  // closes the channel (Client has no public close() of its own)
```

{% endtab %}

{% tab title="Rust" %}

```
drop(stream); // dropping a tonic response stream sends RST_STREAM
drop(sink);   // the write half of the same RPC
drop(client); // closes the channel
```

{% endtab %}
{% endtabs %}

{% hint style="danger" %}
**Reversing the order:** calling `client.close()` before `stream.cancel()` can leave a lingering connection, since the graceful close has to wait on the stream that's still open.
{% endhint %}

Rust's client splits the one JS `stream` object into a read half (`stream`) and a write half (`sink`). Dropping both together is the equivalent of the single `stream.cancel()` call in the TypeScript version.

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import "dotenv/config";
import Client, { CommitmentLevel, SubscribeRequest, SubscribeUpdate } from "@triton-one/yellowstone-grpc";
import { ClientDuplexStream } from "@grpc/grpc-js";

if (!process.env.ENDPOINT || !process.env.X_TOKEN) {
  console.error("error: missing required ENDPOINT / X_TOKEN (set in .env)");
  process.exit(2);
}
const ENDPOINT = process.env.ENDPOINT as string;
const X_TOKEN = process.env.X_TOKEN as string;

const STREAM_FOR_MS = 10000;
const WAIT_AFTER_DISCONNECT_MS = 10000;

const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

type GeyserStream = ClientDuplexStream<SubscribeRequest, SubscribeUpdate>;

function subscribeRequest(): SubscribeRequest {
  return {
    accounts: {},
    slots: {},
    transactions: {
      client: {
        vote: false,
        failed: false,
        accountInclude: ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"],
        accountExclude: [],
        accountRequired: [],
      },
    },
    transactionsStatus: {},
    blocks: {},
    blocksMeta: {},
    entry: {},
    accountsDataSlice: [],
    commitment: CommitmentLevel.PROCESSED,
  };
}

function waitReady(client: Client, timeoutMs: number): Promise<void> {
  return new Promise((resolve, reject) => {
    (client as any)._client.waitForReady(Date.now() + timeoutMs, (err?: Error) =>
      err ? reject(err) : resolve()
    );
  });
}

async function connect(): Promise<{ client: Client; stream: GeyserStream }> {
  console.log(`connecting to ${ENDPOINT} ...`);
  const client = new Client(ENDPOINT, X_TOKEN, {
    "grpc.use_local_subchannel_pool": 1,
    "grpc.max_receive_message_length": 64 * 1024 * 1024,
  });
  await waitReady(client, 10_000);
  console.log("channel ready");

  const stream: GeyserStream = await client.subscribe();
  await new Promise<void>((resolve, reject) =>
    stream.write(subscribeRequest(), (err?: Error | null) => (err ? reject(err) : resolve()))
  );
  console.log("subscribe request sent");

  return { client, stream };
}

function disconnect(client: Client, stream: GeyserStream): void {
  console.log("disconnecting: stream.cancel() then client._client.close()");
  // stream.cancel() first: tells the server directly (RST_STREAM) that this stream is
  // gone. Order matters — client._client.close() is a graceful HTTP/2 shutdown that
  // waits for open streams to finish on their own, so cancelling the stream first means
  // it has nothing left to wait on.
  stream.cancel();
  // client._client.close() closes the underlying channel (the TCP/HTTP2 connection).
  // The public Client class doesn't expose a close() of its own, so this reaches into
  // the grpc-js client it wraps.
  (client as any)._client.close();
  console.log("disconnected");
}

async function main(): Promise<void> {
  const { client, stream } = await connect();

  let txCount = 0;
  stream.on("data", (update: SubscribeUpdate) => {
    if (update.transaction) {
      txCount++;
      console.log(`tx #${txCount} slot=${update.transaction.slot}`);
    }
  });
  stream.on("end", () => console.log("stream 'end' fired"));
  stream.on("close", () => console.log("stream 'close' fired"));
  stream.on("error", (e: Error) => console.log(`stream 'error' fired: ${e.message}`));

  console.log(`streaming for ${STREAM_FOR_MS}ms before disconnecting ...`);
  await sleep(STREAM_FOR_MS);

  disconnect(client, stream);
  console.log(`received ${txCount} transaction(s) before disconnecting`);

  console.log(`watching for ${WAIT_AFTER_DISCONNECT_MS}ms after disconnect ...`);
  await sleep(WAIT_AFTER_DISCONNECT_MS);
  console.log("Closing program after 5");

  process.exit(0);
}

main().catch((e) => {
  console.error(`Error: ${e instanceof Error ? e.message : String(e)}`);
  process.exit(1);
});

```

{% endtab %}

{% tab title="Rust" %}

```rust
use {
    anyhow::Context,
    futures::stream::StreamExt,
    std::{collections::HashMap, time::Duration},
    tonic::transport::channel::ClientTlsConfig,
    yellowstone_grpc_client::{GeyserGrpcClient, GeyserStream, SubscribeRequestSink},
    yellowstone_grpc_proto::prelude::{
        subscribe_update::UpdateOneof, CommitmentLevel, SubscribeRequest,
        SubscribeRequestFilterTransactions,
    },
};

const ACCOUNT_INCLUDE: &[&str] = &["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"];
const STREAM_FOR_MS: u64 = 10_000;
const WAIT_AFTER_DISCONNECT_MS: u64 = 10_000;

fn subscribe_request() -> SubscribeRequest {
    let mut transactions = HashMap::new();
    transactions.insert(
        "client".to_owned(),
        SubscribeRequestFilterTransactions {
            vote: Some(false),
            failed: Some(false),
            account_include: ACCOUNT_INCLUDE.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        },
    );
    SubscribeRequest {
        transactions,
        commitment: Some(CommitmentLevel::Processed as i32),
        ..Default::default()
    }
}

async fn connect(
    endpoint: &str,
    x_token: &str,
) -> anyhow::Result<(GeyserGrpcClient, SubscribeRequestSink, GeyserStream)> {
    println!("connecting to {endpoint} ...");
    let mut client = GeyserGrpcClient::build_from_shared(endpoint.to_owned())?
        .x_token(Some(x_token.to_owned()))?
        .connect_timeout(Duration::from_secs(10))
        .tls_config(ClientTlsConfig::new().with_native_roots())?
        .connect()
        .await
        .context("connect")?;
    println!("channel ready");

    let (sink, stream) = client
        .subscribe_with_request(Some(subscribe_request()))
        .await
        .context("subscribe")?;
    println!("subscribe request sent");

    Ok((client, sink, stream))
}

fn disconnect(client: GeyserGrpcClient, sink: SubscribeRequestSink, stream: GeyserStream) {
    println!("disconnecting: drop(stream)+drop(sink) then drop(client)");
    // drop(stream)+drop(sink) first: dropping a tonic response stream sends RST_STREAM,
    // telling the server directly that this stream is gone. Order matters — dropping the
    // client is a graceful HTTP/2 shutdown that waits for open streams to finish on their
    // own, so dropping the stream/sink first means it has nothing left to wait on.
    drop(stream);
    drop(sink);
    // Dropping the client closes the underlying channel (the TCP/HTTP2 connection) — the
    // Rust analog of client._client.close() in the JS version.
    drop(client);
    println!("disconnected");
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    dotenvy::dotenv().ok();

    let endpoint = std::env::var("ENDPOINT").ok();
    let x_token = std::env::var("X_TOKEN").ok();
    let (Some(endpoint), Some(x_token)) = (endpoint, x_token) else {
        eprintln!("error: missing required ENDPOINT / X_TOKEN (set in .env)");
        std::process::exit(2);
    };

    let (client, sink, mut stream) = connect(&endpoint, &x_token).await?;

    let mut tx_count: u64 = 0;
    let stream_timer = tokio::time::sleep(Duration::from_millis(STREAM_FOR_MS));
    tokio::pin!(stream_timer);

    println!("streaming for {STREAM_FOR_MS}ms before disconnecting ...");
    loop {
        tokio::select! {
            _ = &mut stream_timer => break,
            msg = stream.next() => match msg {
                None => {
                    println!("stream 'end' fired");
                    break;
                }
                Some(Err(e)) => {
                    println!("stream 'error' fired: {e}");
                    break;
                }
                Some(Ok(update)) => {
                    if let Some(UpdateOneof::Transaction(tx)) = update.update_oneof {
                        tx_count += 1;
                        println!("tx #{tx_count} slot={}", tx.slot);
                    }
                }
            }
        }
    }

    disconnect(client, sink, stream);
    println!("received {tx_count} transaction(s) before disconnecting");

    println!("watching for {WAIT_AFTER_DISCONNECT_MS}ms after disconnect ...");
    tokio::time::sleep(Duration::from_millis(WAIT_AFTER_DISCONNECT_MS)).await;
    println!("Closing program after 5");

    Ok(())
}
```

{% endtab %}
{% endtabs %}
