You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS部署Heroku遇R14内存超限错误,添加Twilio后部署失败

NestJS 集成Twilio后Heroku部署触发R14内存超限错误的排查与解决

问题描述

此前已成功在Heroku部署NestJS后端应用,集成Twilio短信服务后部署失败,控制台报错:

Process running mem=973M(190.2%)
Error R14 (Memory quota exceeded)
Stopping all processes with SIGTERM
Process exited with status 143

已尝试执行以下命令,但问题未解决:

heroku config:set NODE_OPTIONS="--max_old_space_size=2560"

应用package.json内容

{
  "scripts": {
    "prebuild": "rimraf dist",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "build": "nest build",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js --config src/utils/ormconfig.ts",
    "migration:generate": "npm run build && npm run typeorm migration:generate -- -n db",
    "migration:run": "npm run build && npm run typeorm migration:run"
  },
  "dependencies": {
    "@nestjs/cli": "^9.1.4",
    "@nestjs/common": "^9.1.4",
    "@nestjs/config": "^2.2.0",
    "@nestjs/core": "^9.1.4",
    "@nestjs/jwt": "^9.0.0",
    "@nestjs/mapped-types": "*",
    "@nestjs/passport": "^9.0.0",
    "@nestjs/platform-express": "^9.1.4",
    "@nestjs/platform-socket.io": "^9.1.4",
    "@nestjs/swagger": "^6.1.2",
    "@nestjs/typeorm": "^9.0.1",
    "@nestjs/websockets": "^9.1.4",
    "@types/socket.io": "^3.0.2",
    "aws-node-sns": "^0.0.3",
    "aws-sdk": "^2.1241.0",
    "bcrypt": "^5.1.0",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.13.2",
    "firebase-admin": "^11.1.0",
    "kkiapay-nodejs-sdk": "github:kkiapay/nodejs-sdk",
    "passport": "^0.6.0",
    "passport-headerapikey": "^1.2.2",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "pg": "^8.8.0",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.5.7",
    "swagger-ui-express": "^4.5.0",
    "typeorm": "^0.3.10"
  },
  "devDependencies": {
    "@nestjs/schematics": "^9.0.3",
    "@nestjs/testing": "^9.1.4",
    "@types/bcrypt": "^5.0.0",
    "@types/dotenv": "^8.2.0",
    "@types/express": "^4.17.14",
    "@types/jest": "29.1.2",
    "@types/node": "^18.11.0",
    "@types/passport-jwt": "^3.0.7",
    "@types/passport-local": "^1.0.34",
    "jest": "29.2.0",
    "prettier": "^2.7.1",
    "source-map-support": "^0.5.21",
    "supertest": "^6.3.0",
    "ts-jest": "29.0.3",
    "ts-loader": "^9.4.1",
    "ts-node": "^10.9.1",
    "tsconfig-paths": "4.1.0",
    "typescript": "^4.8.4"
  },
  "engines": {
    "node": "16.14.0",
    "npm": "8.5.2"
  }
}

排查与解决步骤

1. 修正Twilio客户端初始化方式

Twilio SDK重复创建实例会导致内存累积,必须保证全局单例初始化:

// src/twilio/twilio.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import twilio from 'twilio';

@Injectable()
export class TwilioService {
  private readonly client;

  constructor(private configService: ConfigService) {
    // 仅初始化一次客户端
    this.client = twilio(
      configService.get('TWILIO_ACCOUNT_SID'),
      configService.get('TWILIO_AUTH_TOKEN'),
    );
  }

  async sendSms(to: string, body: string) {
    return this.client.messages.create({
      body,
      from: this.configService.get('TWILIO_PHONE_NUMBER'),
      to,
    });
  }
}

2. 调整Node内存限制至符合Heroku配额

你之前设置的2560MB远超Heroku基础层512MB的配额,反而会让Node尝试占用超出允许的内存,应降低限制:

heroku config:set NODE_OPTIONS="--max_old_space_size=400"

同时添加Procfile指定生产环境启动命令,避免Heroku默认使用开发模式:

web: npm run start:prod

3. 优化依赖与服务的内存占用

  • 检查Firebase Admin、AWS SDK等服务,确保均为全局单例初始化,避免重复创建连接
  • 降低TypeORM连接池大小,减少数据库连接占用的内存:
// src/utils/ormconfig.ts
export default {
  // 其他配置...
  extra: {
    max: process.env.NODE_ENV === 'production' ? 5 : 10, // 生产环境缩小连接池
  },
};

4. 启用NestJS生产模式优化

在main.ts中关闭冗余日志、启用 shutdown hooks,减少运行时内存开销:

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: process.env.NODE_ENV === 'production' ? ['error', 'warn'] : ['debug', 'log', 'verbose'],
  });
  app.enableShutdownHooks();
  await app.listen(process.env.PORT || 3000);
}
bootstrap();

5. 升级Heroku Dyno规格(可选)

若以上优化后内存仍超限,可考虑升级至Standard 1X Dyno(1GB内存),但会产生对应费用。

内容的提问来源于stack exchange,提问作者toundji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:41:03