Skip to content

Instantly share code, notes, and snippets.

@SebDuf
Last active July 25, 2025 17:58
Show Gist options
  • Select an option

  • Save SebDuf/0063fe1e6333e6a0c88ba6d688ef9bbc to your computer and use it in GitHub Desktop.

Select an option

Save SebDuf/0063fe1e6333e6a0c88ba6d688ef9bbc to your computer and use it in GitHub Desktop.
Railway - Simple restart service every day

Restart Railway service every day automatically

  1. Create a new API token (Account Settings --> Tokens --> New Token)
  2. Create a new Function service
  3. In the Variables tab, add a New Variable named RAILWAY_API_TOKEN, and paste your newly created token as the value
  4. In the Source Code tab, put the following script:
interface GraphQLResponse<T> {
  data?: T;
  errors?: { message: string }[];
}

interface RedeployData {
  serviceInstanceRedeploy: boolean;
}

const apiToken = process.env.RAILWAY_API_TOKEN;
const environmentId = process.env.RAILWAY_ENVIRONMENT_ID;
const serviceId: string = /* TODO: Put your service id here */;

if (!apiToken || !environmentId) {
  console.error(
    "Error: Please set RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID environment variables."
  );
  process.exit(1);
}

const graphqlUrl = "https://backboard.railway.app/graphql/v2";

const redeployMutation = `
  mutation serviceInstanceRedeploy($environmentId: String!, $serviceId: String!) {
    serviceInstanceRedeploy(environmentId: $environmentId, serviceId: $serviceId)
  }
`;

const requestBody = JSON.stringify({
  query: redeployMutation,
  variables: { environmentId, serviceId },
});

console.log(
  `Triggering redeployment for service ${serviceId} in environment ${environmentId}...`
);

try {
  const response: Response = await fetch(graphqlUrl, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiToken}`,
      "Content-Type": "application/json",
    },
    body: requestBody,
  });

  const result = (await response.json()) as GraphQLResponse<RedeployData>;

  if (result.errors) {
    const errorMessages = result.errors.map((e) => e.message).join("\n");
    throw new Error(`GraphQL Error:\n${errorMessages}`);
  }

  if (!response.ok) {
    throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
  }

  console.log("Redeployment initiated successfully:", result.data);
} catch (error) {
  if (error instanceof Error) {
    console.error("Failed to trigger redeployment:", error.message);
  } else {
    console.error("An unknown error occurred:", error);
  }
}
  1. In the Settings tab, scroll down to the Cron Schedule section and put the cron you want. Cron is UTC-based, so a restart every day at 3am EST would be 0 7 * * *

That's all!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment