> 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-yellowstone-grpc/docs/getting-started/gracefully-closing-a-grpc-connection.md).

# Closing a gRPC Connection

Solana gRPC Geyser Guide – How to Properly Close Subscription Streams on Yellowstone Connections

Once the subscription stream is active, we can close it using `stream.cancel()` method. A connection can be gracefully closed in two steps:

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

When `stream.cancel()` is called, it triggers an `error` event with a message like "Cancelled" or error code `1`, which indicates a <mark style="color:yellow;">user-initiated shutdown</mark>. We listen for this event, identify it as intentional, and treat it as a normal closure rather than an actual error. Additionally, we listen for the `close` event to ensure the stream has fully terminated on the client side.

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

```
stream.cancel();                  // RST_STREAM — informs the server 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="success" %}
This clean cancellation helps release server-side resources and ensures that any connection tracking (like tokens or sessions) can be properly cleaned up in middleware or proxy layers.&#x20;
{% endhint %}

{% 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 %}

You can paste this code in Replit to see it in action, or simply run the Repl [code here](https://replit.com/@shyft-to/closing-a-grpc-connection?v=1).

{% tabs %}
{% tab title="TypeScript" %}
{% code overflow="wrap" %}

```typescript
import Client, {
  CommitmentLevel,
  SubscribeRequestAccountsDataSlice,
  SubscribeRequestFilterAccounts,
  SubscribeRequestFilterBlocks,
  SubscribeRequestFilterBlocksMeta,
  SubscribeRequestFilterEntry,
  SubscribeRequestFilterSlots,
  SubscribeRequestFilterTransactions,
} from "@triton-one/yellowstone-grpc";
import bs58 from "bs58";

const PUBLIC_KEY_TO_LISTEN = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"; //can be any address
const RUN_TIME = 5000; //decides how long to run
const GRPC_ENDPOINT = "https://grpc.ams.shyft.to"; //your gRPC endpoint
const X_TOKEN = ""; //your x-token

interface SubscribeRequest {
  accounts: { [key: string]: SubscribeRequestFilterAccounts };
  slots: { [key: string]: SubscribeRequestFilterSlots };
  transactions: { [key: string]: SubscribeRequestFilterTransactions };
  transactionsStatus: { [key: string]: SubscribeRequestFilterTransactions };
  blocks: { [key: string]: SubscribeRequestFilterBlocks };
  blocksMeta: { [key: string]: SubscribeRequestFilterBlocksMeta };
  entry: { [key: string]: SubscribeRequestFilterEntry };
  commitment?: CommitmentLevel | undefined;
  accountsDataSlice: SubscribeRequestAccountsDataSlice[];
}

const client = new Client(GRPC_ENDPOINT, X_TOKEN, undefined);

const req: SubscribeRequest = {
  accounts: {},
  slots: {},
  transactions: {
    raydiumLiquidityPoolV4: {
      vote: false,
      failed: false,
      signature: undefined,
      accountInclude: [PUBLIC_KEY_TO_LISTEN],
      accountExclude: [],
      accountRequired: [],
    },
  },
  transactionsStatus: {},
  entry: {},
  blocks: {},
  blocksMeta: {},
  accountsDataSlice: [],
  commitment: CommitmentLevel.PROCESSED,
};

async function handleStream(client: Client, args: SubscribeRequest) {
  console.log(`Subscribing and starting stream...`);
  const stream = await client.subscribe();
  console.log(`Streaming data and printing transactions...`);

  const streamClosed = new Promise<void>((resolve, reject) => {
    stream.on("error", (err: any) => {
      if (err.code === 1 || err.message.includes("Cancelled")) {
        //this indicates stream was cancelled by user.
        console.log("✅ Stream cancelled by user");
        resolve();
      } else {
        console.error("❌ Stream error:", err);
        reject(err);
      }
    });

    stream.on("close", () => {
      console.log("Stream closed.");
      resolve();
    });
  });

  stream.on("data", (data) => {
    if (data.transaction) {
      console.log(
        "Received: ",
        bs58.encode(data.transaction.transaction.signature),
      );
    }
  });

  // Subscribe
  stream.write(args);

  // Cancel after timeout
  setTimeout(() => {
    console.log("Cancelling stream...");
    try {
      stream.cancel();
      /*
       * stream.end() or stream.destroy();
       * Cancels the stream from the user end, and closes the stream.
       *
       * A "Cancelled on client" error (code 1) will be thrown once this is called,
       * which be caught in stream.on("error") function.
       * This is one of the ways to cancel the stream, and clear your connections, when using Shyft gRPCs.
       *
       * For more information on clearing connections, please check the FAQ section of gRPC docs
       * https://docs.shyft.to/solana-yellowstone-grpc/grpc-docs#solana-grpc-faq
       */
    } catch (error) {
      if (error.code !== "ERR_STREAM_PREMATURE_CLOSE") {
        console.error("Stream cancel error:", error);
      }
    }
  }, RUN_TIME);

  await streamClosed;
}

async function subscribeCommand(client: Client, args: SubscribeRequest) {
  await handleStream(client, args);
}

subscribeCommand(client, req);
```

{% endcode %}
{% 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)");
    // Step 1: cancel the stream. Dropping the response half of a Yellowstone gRPC
    // Subscribe RPC sends an HTTP/2 RST_STREAM, telling the server directly that this
    // stream is gone. Order matters — closing the channel is a graceful HTTP/2 shutdown
    // that waits for open streams to finish on their own, so cancelling the stream first
    // means there's nothing left for it to wait on.
    drop(stream);
    drop(sink);
    // Step 2: close the channel. Dropping the client drops the last handle to the
    // underlying HTTP/2 connection to the Yellowstone gRPC server, closing it.
    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;

    Ok(())
}
```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
The complete code of closing a connection is available on [Replit here](https://replit.com/@shyft-to/closing-a-grpc-connection?v=1).
{% endhint %}

Please note that we can also use `stream.destroy()` to end and destroy the stream. When using this, the streaming does stop, but the connection is not terminated, and hence it is not useful in certain cases.
