Deploying a Realtime App

This is a simple example of a realtime streaming app. When deployed, this app will be exposed as a public websocket endpoint.

realtime accepts a single parameter, called event, with the event payload.

The realtime decorator is an abstraction above asgi.

This means that additional parameters in asgi, such as concurrent_requests can be used too.

app.py
from beam import realtime


@realtime(
    cpu=1,
    memory="1Gi",
    concurrent_requests=10, # Process 10 requests at a time 
    authorized=False, # Don't require auth to invoke 
)
def stream(event):
    # Echo back the event payload sent to the websocket
    return {"response": event}

This app can be deployed in traditional Beam fashion:

beam deploy app.py:stream

Streaming Responses from the Client

The code below uses the Beam Javascript SDK to send requests to the realtime app.

Make sure to add an .env file to your project with your BEAM_DEPLOYMENT_ID and BEAM_TOKEN:

client.js
import beam from "@beamcloud/beam-js";

const streamResponse = async () => {
  const client = await beam.init(process.env.BEAM_TOKEN);
  const deployment = await client.deployments.get({ id: process.env.BEAM_DEPLOYMENT_ID });

  const connection = await deployment.realtime();
  
  const payload = {
    "event": "Echo this back",
  }

  connection.onmessage = (message) => {
      console.log(`🎉 Response: ${message.data}`);
  };

  connection.send(JSON.stringify(payload));

  setTimeout(() => {
    connection.close();
  }, 1000);
};

streamResponse();