Managing Effect Layers Efficiently in an API Server Setup

Hello everyone
I have a question regarding requirements management
I've built an api server, and I have a lot of controllers in which I provide the implementation of corresponding services

f.e:
questions.controller.ts
app.get(
  "/:presentationId",
  sValidator(
    "param",
    Schema.standardSchemaV1(
      Schema.Struct({
        presentationId: Schema.String,
      }),
    ),
  ),
  async (c) => {
    const presentationId = c.req.valid("param").presentationId;

    const result = await Effect.runPromiseExit(
      Effect.gen(function* () {
        const questionsService = yield* QuestionsService;

        return yield* questionsService.getPageInfo(presentationId);
      }).pipe(
        Effect.provide(QuestionsServiceLive.pipe(Layer.provide(DatabaseLive))),
      ),
    );

    const value = getValueOrThrowHonoError(result, (error) => {
      Match.type<typeof error>().pipe(
        Match.tag("QuestionNotFoundError", (error) => {
          throw new HTTPException(404, {
            cause: error.cause,
            message: `Question with id ${error.questionId} not found`,
          });
        }),
        Match.orElse(() => {
          throw new HTTPException(500, {
            cause: error.cause,
            message: error.message,
          });
        }),
      )(error);
    });

    return c.json(value);
  },
);


the problem with this is that my DatabaseLive along with QuestionsServiceLive layers will be re-created each time a new request comes in.
I understand that I probably have somewhat wrong approach to managing all of this, and I should probably make my whole api to run in one shared fiber, which will then provide the correct context to each of the controllers

But I struggle to come up with the solution that will work with the api library Im using?
Would really appreciate if someone will lead me to the right direction!
Was this page helpful?