iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐣

The Tech Stack of Sizukana Internet

に公開
2025/09/11
18件

I've released a web service like this, so I'd like to summarize the technical side of it.

https://sizu.me?ref=zenn

Originally, I started developing this service as something of an extension of a hobby. Considering that competitors like note and Hatena Blog have already established solid positions, I'm continuing development with a relaxed mindset: "It probably won't make money, but I'll make it something filled with my own interests" (It's fun).

Selection Policy

Even though it's a hobby, it is a writing service, so I have to operate it for a long period even if there are only a few users. Therefore, I made selections so that if the number of users is small, the running cost is less than a few thousand yen per month, and as the number of users increases, the cost rises incrementally.

Application

I am deploying a full-stack Next.js application to Cloud Run. Each API endpoint is created using Next.js API Routes.

Regarding Next.js, I am using the Pages Router instead of the App Router. I attempted to switch to the App Router partway through, but I decided against it for various reasons.

Reasons for deciding against it

The situation might have changed now, but I decided against adopting the App Router for the following reasons:

  • Shallow Routes did not exist (Just changing the query string caused the server processing to re-run. This was not resolved even if I moved the data fetching from page.tsx to layout.tsx).
  • In server-side data fetching, even when wrapping function calls with the same arguments in cache(), they were sometimes executed twice within a single request (Sometimes they weren't, and I disliked debugging that. I really wanted to avoid "silently executing the same query to the DB multiple times" in a production environment. Related Tweet).
  • I wanted to use Intercepting Routes, but the experience—such as the scroll position on browser back and flickering—was not great (In the end, I implemented my own version of Intercepting Routes using the Pages Router).

Screenshot of the abandoned PR

Database

PlanetScale

I use PlanetScale (MySQL) as the main database. PlanetScale has a generous free tier, and for this service, a $29/month plan could cover it until it scales significantly (with the 2024 price revision, the minimum price for the Tokyo region became $47/month). Since usage exceeding the plan's limit is charged based on consumption, there is no worry about the price suddenly skyrocketing.

In PlanetScale, the number of rows read significantly affects the cost, so efficient queries and appropriate indexes are important.

PlanetScale Dashboard Query Insights

The great thing is that you can check the latency and the number of rows read for each query from the Query Insights on the dashboard (and you can even run EXPLAIN directly from there!).

Drawbacks

The only drawback is that performance is worse when connecting to PlanetScale from Cloud Run compared to using Google Cloud's databases (such as Cloud SQL). In my personal verification, even when both regions were set to Tokyo, the wait time was about 10–20ms longer per query.

Since I decided to prioritize cost above all else this time, I accepted this as inevitable and am trying to reduce the frequency of data retrieval from the DB as much as possible or execute it simultaneously with other asynchronous processes.

ORM

I am using Prisma.

Upstash

For rate limiting of some operations and some caching, I use Upstash Redis. Similarly, the latency is inevitably higher when accessed from Cloud Run compared to using Google Cloud's Redis service, but I accept this as a necessary compromise.

CDN

I use Cloudflare as the CDN for cost reasons. I set long cache headers for static files like CSS, JS, and images, and if a purge is needed, I either change the resource URL or perform a bulk purge.

Cloudflare Workers

To address the latency issue that occurs when linking a custom domain directly to Cloud Run, I have set the custom domain on Cloudflare Workers and use it to proxy requests (excluding static files) to Cloud Run.

https://zenn.dev/catnose99/scraps/ffdd08cebfad12

While using Cloud Load Balancing would result in even faster responses, I settled on this configuration to balance running costs and performance.

Preconnect for static file URLs

I use a different domain for static file URLs than sizu.me. In addition to Cloudflare plan constraints, this also serves the purpose of preventing unnecessary cookies (especially authentication-related cookies) from being attached to requests for static files.

Since that requires separate DNS Prefetching for the static file domain, I use <link rel="preconnect" /> and 103 Early Hints to ensure requests start as early as possible.

https://zenn.dev/catnose99/scraps/1566bbc77f5bb9

Object Storage

I use Cloudflare R2 due to its low cost. A concern with R2 is that it doesn't currently support features like versioning, which makes it scary if a file were to be accidentally deleted.

As a precaution, I periodically run rclone via Cloud Run Jobs to back up files on R2 to Cloud Storage (using the cheapest archive class). I wrote more details about this in the following article.

https://zenn.dev/catnose99/articles/c0c710f98a0be8

Payment

I use Stripe. I issue a Checkout Session URL so that users can complete the payment process on Stripe's site. The service's database holds almost no payment-related information, maintaining only whether a "subscription is active" for caching purposes (synchronized via a Webhook handler).

Logging and Error Notifications

On Cloud Run, you can output structured logs using console.log.

https://zenn.dev/moga/articles/cloudrun-structured-log

When an error occurs, I have configured two types of notifications to be sent to Slack depending on the log level (severity).

  • error: Posted to the #prod-error channel. I check these during my next work session.
  • critical: Posted to the #prod-critical channel with a mention. These are output only in rare cases, such as inconsistencies in payments. I check these immediately.

The following article was helpful for setting up the notifications.

https://zenn.dev/team_zenn/articles/cloud-logging-log-alert

Secret Management

Secrets referenced from the server runtime are managed with Secret Manager. Unexpectedly, it costs a few hundred yen per month.

Asynchronous and Batch Processing

On Cloud Run, in addition to the main service, I deploy a task service that only accepts requests from within Google Cloud.

Some time-consuming processes are handled asynchronously in the task service using Cloud Tasks. Batch processing is executed by periodically sending HTTP requests from Cloud Scheduler to the task service.

Email Delivery

I chose AWS SES based on the balance between cost and reliability. Applying for a limit increase and setting up SPF/DKIM/DMARC was a bit of a hassle, but it was a good learning experience. I actually wanted to use SendGrid or Resend, but it couldn't be helped.

By the way, email delivery processes are triggered by Cloud Scheduler. Since Cloud Scheduler follows an "at-least-once" (at least one execution) specification, there is a possibility of duplicate executions. To avoid sending the same email twice, I use Redis for mutual exclusion before sending the email.

CI/CD

When a pull request is created, tests and linting are executed via GitHub Actions. Upon merging into the main branch, Cloud Build runs and automatically deploys to Cloud Run.

IaC

The settings for each Google Cloud service are managed using Terraform. Managing them with code provides a sense of security (I learned about the appeal of Terraform from waddy_u while I was on the Zenn development team).

Authentication

I use a combination of NextAuth and Firebase Authentication. However, when combining Firebase Auth (signInWithRedirect) with NextAuth for Google login, the wait time for users sometimes exceeded 5 seconds, resulting in a very poor experience. Therefore, I decided to use Google login directly without going through Firebase Authentication.

This is my personal speculation, but I suspect the reason signInWithRedirect in Firebase Auth has become slower (?) is that it now requires more internal "gymnastics" to handle authentication between Firebase domains while third-party cookies are being blocked (Reference: Best practices for using signInWithRedirect on browsers that block third-party cookies).

Styling

I mainly use Tailwind CSS. For parts that require animations or other specific needs, I use CSS Modules.

Data Fetching / State Management

For API requests from the client, I use trpc. I chose trpc because the developer experience, such as TypeScript type completion, is excellent. trpc also provides a wrapper package for react-query, which makes writing data fetching and update logic very easy.

I also try to handle state management on the client using react-query as much as possible. For certain states that don't involve data fetching, I use jotai. jotai is great because of its small bundle size.

Image Resizing

Considering the possibility of migrating from Next.js to another framework in the future, I tried to avoid using "special" features like next/image or ISR as much as possible. For image resizing, I set up a dedicated API endpoint where you can pass the image URL and configuration values via query strings to receive a resized image.

# Concept
/api/resize-image/signature?url=original_image_url&width=200

The signature included in the URL is generated on the server-side from the query string, and an error is returned if the query string is tampered with.

Dynamic OG Image Generation

OG images for each user are generated using satori. I include a signature in the URL for these as well to prevent third parties from tampering with the images.

By the way, since the display of X's summary_large_image format link cards became a bit awkward, I ended up only generating square images for the summary format.

https://catnose.me/notes/use-summary

Editor

I use TipTap for the article editor. I like it a lot because it has detailed documentation, the code is easy to read, and it's easy to extend (if necessary, you can directly access the API of ProseMirror, which is used internally).

Testing

I mainly focus on backend testing (I just counted, and there are 530 test cases). I use Vitest and React Testing Library as libraries. Since I didn't want to mock the database, I prepared a test DB and reset it before each run.

I use a library called prisma-fabbrica for inserting test data. I think the test code has become much more concise thanks to prisma-fabbrica.


As you can see, the technical stack involves many moving parts. If I hadn't worried about costs, I could have released it sooner, made the loading speed faster, and kept the architecture simpler, but that's just the trade-off I made.

I intend to keep up with technological advancements at a relaxed pace and continue making improvements little by little.

Discussion

MelodyclueMelodyclue

ステージング環境って作っていますか?(Cloud Deploy?など...)

6
catnosecatnose

Google Cloudのプロジェクト自体を切り替える形でステージング環境を作っています。構成やデプロイ方法などは本番環境と同じです。

6
kyeshmzkyeshmz

なぜResendやSendgridを選択しなかったのか伺いたいです! Dedicated IPの料金とかでしょうか

1
catnosecatnose

料金です。Dedicated IPを除いてもAWS SESがコスト的にベストだと判断しました。

3
MCタツノボリMCタツノボリ

お答えいただける範囲で構わないのですが、ムードの音声はHTMLのaudioタグで再生とループさせてますでしょうか?

自分の手元で試しにやってみてるのですがaudioタグのループだとぶつ切り感があってしずかなインターネットのムードのように綺麗に繋がらないので、聞いてみた次第です!

AsaAsa

こちら、UIライブラリやスタイリングなどは何を選択しているでしょうか?

catnosecatnose

TailwindCSSを使っています!UIライブラリはポップオーバーにfloating-uiを使ってるくらいですかね。

5
AsaAsa

ご返信ありがとうございます!
似たような質問で申し訳ありませんが、Headless UIやコンポーネントライブラリなどは使用していない 
認識でよろしいでしょうか?

catnosecatnose

はい、使っていません。そのようなコンポーネントライブラリは個人開発では基本的に使わないですね。

AsaAsa

もし、可能であればコンポーネントライブラリを個人開発で使わない理由について
お聞かせいただきたいです。

catnosecatnose

https://mond.how/ja/topics/mwcwkx25fy471t8

以前こちらに書きました。UIライブラリに関わらず、自分で実装できるものはできる限り入れない方針です。バンドルサイズが必要以上に大きくなったり、アップデートに気を遣ったりするのがいやなので

7
AsaAsa

ありがとうございます!!とても参考になりました!
1月23日にあるcatnoseさんのイベント楽しみにしています!

2
つきみつきみ

質問失礼します!

記事での$29はおそらく、Scalerプランを指しているかと思いますが、現在ではこちらのプランは廃止されてしまい、$39〜のProプランのみとなってしまったのはご存知かと思います。
そこで、もし今後Scalerがプランが全面的に廃止されるとなった時、
ブランチや高速性、快適性などを考えて$39〜でもPayすると言ったことは考えていますか?
(もうすでにProプランに切り替えていましたらごめんなさい!)

また、公開できる範囲で構わないのですが、全体的にどれくらいのアクセス量をどれくらいの費用で賄っているなどもお聞きしたいです!

これからもしずかなインターネットを使っていきます!

catnosecatnose

今から他のクラウドサービスに移行するのはできるかぎり避けたいので、$39〜でも利用することになると思います。

どれくらいのアクセス量をどれくらいの費用で賄っているなど

現状だと100〜200万ページビュー/月ですが、Scalerプランでもまだかなり余裕があります。今後はストレージ部分の料金がネックになりそうですが、部分的にオブジェクトストレージに持たせること等も検討しています。

3