<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by letnaturebe on Medium]]></title>
        <description><![CDATA[Stories by letnaturebe on Medium]]></description>
        <link>https://medium.com/@letnaturebe2?source=rss-d7d3fbf712cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8FwX7m11nU0bFjAoeqixNQ.jpeg</url>
            <title>Stories by letnaturebe on Medium</title>
            <link>https://medium.com/@letnaturebe2?source=rss-d7d3fbf712cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:33:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@letnaturebe2/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Sort는 LIMIT을 무시한다 — 목록 조회 37초 버그 잡기]]></title>
            <link>https://medium.com/@letnaturebe2/sort%EB%8A%94-limit%EC%9D%84-%EB%AC%B4%EC%8B%9C%ED%95%9C%EB%8B%A4-%EB%AA%A9%EB%A1%9D-%EC%A1%B0%ED%9A%8C-37%EC%B4%88-%EB%B2%84%EA%B7%B8-%EC%9E%A1%EA%B8%B0-29d3be1658ce?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d3be1658ce</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-tuning]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 11:21:50 GMT</pubDate>
            <atom:updated>2026-08-03T12:40:15.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smAdpy6f_wOx9p1RoF-GNA.png" /></figure><p>주문 목록 조회가 37초 걸린다는 제보를 받았다. 페이지당 20건 보여주는 화면인데, 특정 판매자가 조회하면 너무 느리다고 했다.</p><p>EXPLAIN을 떠보니 예상대로였다. ORDER BY를 인덱스가 제공하지 못해서 정렬이 플랜 최상단에 놓였고, 그래서 LIMIT 20이 무력해지면서 조인이 3만 번 돈다. 목록 조회에서 흔히 나오는 패턴이라 원인 자체는 금방 잡혔다.</p><p>문제는 그 다음이었다. 근거를 만들려고 이것저것 돌려보는데 숫자가 자꾸 어긋났다. WHERE 조건 하나를 지웠더니 37초가 70ms로 떨어졌고, 그래서 됐나 싶었는데 조회 기간을 한 달에서 20일로 좁히자 다시 27초가 나왔다. 읽는 데이터를 줄였는데 오히려 느려진 것이다.</p><p>옵티마이저가 왜 이렇게 오락가락하는지 파봤더니, 알고 있던 ORDER BY 문제 위에 통계와 병렬 처리가 얽혀 있었다. 그 과정을 정리해서 공유한다.</p><h3>기존 목록 조회 쿼리</h3><p>실제 쿼리는 컬럼도 조인도 더 많지만, 읽기 편하게 주문/결제/사용자 정도로 줄여서 옮겼다. 테이블명과 컬럼명도 일반적인 이름으로 바꿨다. 실행계획 수치는 실제 측정값 그대로다.</p><p>목록 화면이니 구조는 뻔하다. 주문을 조건으로 걸러서, 최신순으로, 20건.</p><pre>SELECT o.*, p.*, u.*, c.*<br>  FROM orders o<br>  LEFT JOIN payments p ON o.payment_id = p.id<br>  LEFT JOIN users    u ON o.user_id    = u.id<br>  LEFT JOIN codes    c ON o.status_key = c.key<br> WHERE o.seller_id        = 1<br>   AND o.legacy_seller_id = 2<br>   AND o.store_id         = 3<br>   AND o.closed_at &gt;= &#39;2026-07-01&#39;<br>   AND o.closed_at &lt;  &#39;2026-08-01&#39;<br> ORDER BY o.id DESC<br> LIMIT 20;</pre><p>orders는 3억 건이 넘는 테이블이고 인덱스도 있다.</p><pre>CREATE INDEX idx_orders_closed ON orders (seller_id, store_id, closed_at);</pre><p>legacy_seller_id만 빼면 WHERE에 쓰는 컬럼이 인덱스 앞쪽에 순서대로 다 들어가 있다. 교과서적으로 잘 만든 인덱스다.</p><p>실행계획을 보자.</p><pre>Limit  (actual time=36767..36767 rows=20)<br>  -&gt;  Sort  (actual time=36767..36767 rows=20)<br>        Sort Key: o.id DESC<br>        Sort Method: top-N heapsort  Memory: 33kB<br>        -&gt;  Nested Loop Left Join  (actual time=4.7..36748 rows=36120)<br>              -&gt;  Index Scan using idx_orders_closed on orders o<br>                    Index Cond: (seller_id = 1 AND store_id = 3 AND closed_at &gt;= ...)<br>                    Filter: (legacy_seller_id = 2)<br>                    (actual time=2.6..749 rows=36120)              ← 749ms<br>              -&gt;  Memoize  (actual time=0.000..0.000 loops=36120)  ← codes, 사실상 0<br>                    Hits: 36113  Misses: 7<br>              -&gt;  Index Scan using users_pkey on users u<br>                    (actual time=0.002..0.002 rows=1 loops=36120)  ← 72ms<br>                    Buffers: shared hit=144480<br>              -&gt;  Index Scan using payments_pkey on payments p<br>                    (actual time=0.990..0.990 rows=1 loops=36120)  ← 여기<br>                    Buffers: shared hit=140320 read=42217<br>                    I/O Timings: shared read=35552</pre><p>loops=36120.</p><p>Nested Loop은 바깥쪽 행 하나마다 안쪽을 한 번씩 조회한다. 그러니까 지금 벌어지는 일은 사실상 이거다.</p><pre>-- orders에서 나온 36,120건에 대해 한 건씩<br>SELECT * FROM payments WHERE id = ?;   -- 36,120번 반복<br>SELECT * FROM users    WHERE id = ?;   -- 36,120번 반복<br>SELECT * FROM codes    WHERE key = ?;  -- 36,120번 반복</pre><p>조인 세 개가 전부 36,120번씩 돌았다. 그런데 느린 건 payments 하나뿐이다. 한 번에 0.99ms니까 다 합치면 35.7초, 전체 36.7초의 97%다.</p><p>나머지 둘이 빠른 이유는 캐시다. codes는 상태 코드가 몇 종류밖에 안 되니 Memoize가 36,113번 적중해서 실제로는 7번만 조회했다. users는 Memoize 없이 36,120번 다 돌았지만 read=0, 즉 디스크를 한 번도 안 갔다. 같은 사용자가 반복되고 테이블도 작아서 전부 메모리에 있었다.</p><p>payments만 42,217블록을 디스크에서 읽었다. 주문마다 결제가 다르니 한 번 채운 블록이 다시 쓰이질 않고, 테이블이 커서 블록도 흩어져 있다.</p><p>여기서 짚어둘 게 있다. pkey로 찾는 것 자체는 느리지 않다. B-tree 상위 레벨은 늘 캐시에 있으니 위치를 찾는 건 거의 공짜다. 비용은 그 다음, 찾은 위치의 힙 블록을 실제로 읽어오는 데서 발생한다. 그 블록이 버퍼에 없으면 디스크로 가야 한다.</p><pre>Buffers: shared hit=140320 read=42217<br>                  ↑ 버퍼에 있던 것    ↑ 디스크에서 읽은 것</pre><p>미스율로 보면 23%인데 그 23%가 시간의 97%를 먹었다. read=42217 / loops=36120이니 조회당 1.17블록, 블록당 0.84ms다. 클라우드 스토리지 랜덤 읽기로는 정상 수치다. 디스크가 느린 게 아니라 랜덤 읽기를 4만 번 하면 원래 35초 걸린다.</p><p>그래서 이건 조인 쪽 인덱스 문제가 아니다. payments_pkey는 있고 제대로 타고 있다. NL로 3만 번 도는 것과 그때마다 버퍼에 없는 것, 이 둘이 곱해져서 35.7초가 됐다. 어느 한쪽만 있었으면 괜찮았다. 3만 번이어도 전부 캐시 히트였으면 users처럼 72ms로 끝났을 거고, 캐시 미스여도 20번이었으면 20ms다.</p><p>실제로 같은 조회를 한 번 더 돌리면 버퍼가 채워져서 5초 안쪽으로 떨어지기도 했다. 하지만 이건 그다지 좋은 것은 아닌데, 조회 조건이 바뀌면 다시 디스크에서 가져와야 하고 쓰기가 많은 테이블이라 새 페이지가 계속 캐시를 밀어낸다. 같은 화면이 5초였다 37초였다 하면 원인 추적이 더 어려워질 뿐이다.</p><p>orders 스캔은 749ms밖에 안 걸렸으니 인덱스는 잘못이 없었다. legacy_seller_id가 인덱스에 없어서 Filter로 처리되긴 하는데, 어차피 인덱스로 찾아낸 행에 대해서만 검사하는 것이라 이것도 749ms 안에 들어 있다. 지금은 문제가 아니다.</p><h3>왜 LIMIT 20인데 3만 번을 조인하나</h3><p>20건만 필요한데 왜 36,120건을 전부 조인할까. 답은 Sort에 있다.</p><p>ORDER BY o.id DESC는 마지막 행을 보기 전까지 순서를 확정할 수 없다. 36,120번째 주문의 id가 제일 클 수도 있으니까. 그래서 정렬은 조인이 전부 끝난 뒤에야 시작된다.</p><p>실행계획은 아래에서 위로 읽는다. 아래 노드가 결과를 만들어 위로 올려주는 구조다. 그러니 Sort 밑에 조인이 있다는 건 조인 결과 전체가 Sort로 올라간다는 뜻이고, 조인은 36,120번을 다 돌 수밖에 없다.</p><pre>Limit 20                          ↑ 마지막<br> └ Sort              ← 조인 결과를 전부 받아야 정렬을 시작<br>    └ Nested Loop    ← 먼저 36,120번 전부 실행</pre><p>LIMIT 20은 정렬이 다 끝난 다음에야 일한다. 상식적으로는 20건을 먼저 추리고 그 20건만 조인하면 될 것 같은데, 지금 플랜은 정확히 반대로 돌고 있다.</p><p>플랜에 Sort Method: top-N heapsort Memory: 33kB가 찍혀 있어서 뭔가 잘라준 것 같지만, 자르는 대상이 다르다. top-N heapsort는 LIMIT 20을 알고 있어서 힙에 20개만 유지하고 나머지는 버린다. 그래서 메모리를 33kB만 썼다. 일반 정렬이었으면 몇 MB를 썼을 것이다. 보관할 행 수는 줄여주지만 읽어야 할 행 수는 못 줄인다. 이름에 낚이기 쉬운 지점이다.</p><p>그럼 정렬을 조인보다 먼저 하면 되지 않나? orders만 먼저 정렬해서 20건 추린 다음 그 20건에만 조인하면 된다.</p><pre>Limit 20<br> └ Nested Loop      ← 20번만 실행<br>    └ Sort          ← orders만 정렬<br>       └ Index Scan on orders</pre><p>논리적으로 문제없다. 정렬 키 o.id는 orders에서만 나오고, 나머지 조인은 전부 LEFT JOIN에 pkey 매칭이라 행 수를 늘리거나 줄이지 않는다. Nested Loop은 바깥쪽 순서를 보존하니 순서도 안 깨진다.</p><p>그런데 플래너는 이 플랜을 안 골랐다. 정확히는 후보로 만들지도 않았다. Postgres는 Sort 노드를 아무 데나 끼워넣지 않는다. 조인보다 정렬이 먼저 일어나는 경우, 그러니까 Sort가 조인 밑에 놓이는 경우는 딱 셋뿐이다.</p><ol><li>인덱스가 그 순서를 공짜로 제공할 때</li><li>Merge Join을 위해 양쪽을 정렬할 때</li><li>Gather Merge — 병렬 워커가 각자 정렬하고 순서를 유지하며 병합할 때</li></ol><p>우리 쿼리는 셋 다 아니었다. idx_orders_closed는 (seller_id, store_id, closed_at)이라 id 순서를 못 주고, 조인은 전부 Nested Loop이고, 워커도 안 붙었다. 정렬을 놓을 자리가 플랜 꼭대기밖에 없었다. 선택의 여지가 없어서 그렇게 된 것이지 비교해서 진 게 아니다.</p><h3>Gather Merge는 왜 안 생겼나</h3><p>셋 중에 그나마 기대할 만한 건 3번이다. 1번은 정렬 키를 바꿔야 하고 2번은 이 조인 형태에선 나올 일이 없지만, 병렬은 플래너가 조건만 되면 알아서 붙여주니까. 왜 안 붙었는지 보려고 다시 플랜을 봤는데 이상한 숫자가 있었다.</p><pre>Index Scan using idx_orders_closed on orders o<br>  (cost=0.56..6613.10 rows=52 width=83) (actual ... rows=36120)<br>                      ↑ 추정 52          ↑ 실제 36,120</pre><p>멍청한 옵티마이저가 694배 틀렸다.</p><p>병렬 여부는 이 추정치가 결정한다. 플래너는 추정 행 수로부터 읽어야 할 페이지 수를 계산하고, 그게 임계값(min_parallel_table_scan_size, 기본 8MB)을 넘으면 &quot;이건 큰 작업이니 워커를 붙이자&quot;고 판단한다. 52행이면 페이지 한두 장이니 근처도 못 간다.</p><p>그래서 이렇게 이어진다. 추정치가 작다 → 워커가 안 붙는다 → Gather Merge가 안 생긴다 → orders만 먼저 정렬할 방법이 없다 → 정렬이 꼭대기로 간다 → 조인이 36,120번.</p><p>바꿔 말하면 <strong>추정치만 제대로 나왔어도 병렬이 붙었을 거고, 그러면 정렬이 조인보다 먼저 왔을 것이다.</strong> 실제 36,120행이면 페이지 수가 임계값을 한참 넘으니까.</p><p>그럼 추정치는 왜 틀렸나. WHERE를 다시 보니 조건이 하나 더 있었다.</p><pre>WHERE o.seller_id        = 1<br>  AND o.legacy_seller_id = 2   -- 인덱스에 없어서 힙 필터로 처리되던 조건(seller_id와 동일해서 불필요한 조건, 추정치만 깎음)<br>  AND o.store_id         = 3<br>  ...</pre><p>현재 시스템은 골때리게도 판매자 ID가 이원화되어 있어서 구 ID(seller_id)와 신 ID(legacy_seller_id)를 둘 다 넘기고 있었다.</p><p>그런데 이 둘은 항상 1:1로 짝지어 다닌다. 판매자 A의 구 ID가 1이면 신 ID는 언제나 2다. 숫자만 다를 뿐 같은 판매자를 가리킨다.</p><pre>id    seller_id   legacy_seller_id<br>------------------------------------<br>101       1              2<br>102       1              2<br>103       5              7      ← 다른 판매자는 쌍도 통째로 다르다<br>104       5              7<br><br>seller_id = 1 인데 legacy_seller_id 가 2가 아닌 행은 존재하지 않는다</pre><p>그러니 seller_id = 1로 이미 좁혀놓으면 남은 행은 전부 legacy_seller_id = 2다. 뒤에 AND legacy_seller_id = 2를 붙여도 버려지는 행이 하나도 없다. <strong>실질적으로 필터링을 하지 못하는 조건이다.</strong></p><p>문제는 플래너가 이걸 모른다는 것이다. 두 컬럼의 통계를 따로 갖고 있을 뿐, 둘이 짝지어 다닌다는 사실은 어디에도 저장되어 있지 않다. 확장 통계가 없으면 Postgres는 컬럼 간 조건을 전부 독립으로 보고 선택도를 곱한다. 그래서 694배나 작게 계산한 것이다.</p><pre>추정 = 전체행수 × P(seller_id=1) × P(legacy_seller_id=2) × P(store_id=3) × ...<br>                  └──────────────────────────────────────────┘<br>                     같은 판매자를 가리키는 조건인데 두 번 곱해진다</pre><p><strong>걸러내는 행은 0건인데 추정 계산에만 들어간 것이다.</strong> 실행계획에서도 확인된다. Filter: (legacy_seller_id = 2) 바로 아래에 Rows Removed by Filter: 줄이 없다. EXPLAIN ANALYZE는 필터가 행을 하나라도 버리면 반드시 그 줄을 출력하니, 없다는 건 한 건도 안 버렸다는 뜻이다.</p><p>인덱스에 없는 조건이니 힙 필터일 뿐인데 추정에 영향을 주는 게 이상해 보일 수 있다. 하지만 행 수 추정은 인덱스를 고르기 전에 끝난다. 플래너는 먼저 WHERE 절 전체로 이 테이블에서 몇 행이 나올지 계산하고, 그 다음에 어떤 인덱스로 접근할지 정한다.</p><p>1단계에서는 인덱스가 뭐가 있는지 보지도 않는다. 그러니 Index Cond로 갈 조건이든 Filter로 밀릴 조건이든 똑같이 선택도 곱셈에 참여한다. 위치는 실행할 때 힙을 방문하느냐만 바꾸지 추정에는 관여하지 않는다.</p><p>체인이 이렇게 이어진다.</p><pre>중복 조건<br>  → 추정치 52 (실제 36,120)<br>  → 스캔 페이지 추정 1~2장 → 병렬 임계값 미달<br>  → 워커 0 → Gather Merge 없음<br>  → orders만 먼저 정렬할 방법이 없음<br>  → Sort가 플랜 꼭대기로 → 조인이 그 밑에서 36,120번<br>  → 37초</pre><p>1:1이 확인됐으니 조건 하나는 그냥 지워도 된다. 지웠더니 이렇게 됐다.</p><pre>Limit  (actual time=64.6..70.0 rows=20)                 ← 70ms<br>  -&gt;  Nested Loop Left Join  (rows=20)<br>        -&gt;  ... users / codes 조인 ...  (loops=20)<br>        -&gt;  Index Scan using payments_pkey  (loops=20)  ← 36,120 → 20<br>              Buffers: shared hit=104               ← read=0, 디스크 안 감<br>        -&gt;  Gather Merge  (rows=20)<br>              Workers Planned: 1  Launched: 1           ← 워커 붙음<br>              -&gt;  Sort  Sort Key: o.id DESC  (rows=297 loops=2)<br>                    -&gt;  Parallel Bitmap Heap Scan on orders  (rows=18036 loops=2)<br>                          -&gt;  Bitmap Index Scan  (rows=1648)   ← 추정 52 → 1,648</pre><p><strong>37초에서 70ms.</strong> 500배다.</p><p>아래에서 위로 읽으면 순서가 이렇다.</p><pre>① 워커 2개가 orders를 나눠서 스캔        → 36,120건<br>② 각 워커가 자기 몫을 id DESC로 정렬      → loops=2<br>③ Gather Merge가 순서 유지하며 병합       → &quot;정렬된 orders&quot;<br>④ Limit이 위에서 20건만 당김<br>⑤ 그 20건에만 조인                       → loops=20</pre><p>핵심은 ③에서 조인 없이 정렬이 끝났다는 것이다.</p><p>그래서 ④의 LIMIT 20이 조인 <strong>앞에서</strong> 잘라준다. payments 조회가 36,120번에서 20번이 됐고, 시간의 97%가 거기 있었으니 그대로 사라졌다.</p><p>Buffers: shared hit=104, read=0도 눈에 띈다. 20건이면 디스크에 갈 일조차 없다. 앞에서 42,217블록을 읽던 게 통째로 없어졌다.</p><p>정렬량은 그대로다. 여전히 36,120건을 다 정렬한다. 줄어든 건 <strong>조인 횟수뿐</strong>이다.</p><p>짚어둘 게 둘 있다.</p><p>하나, <strong>지운 조건은 결과를 바꾸지 않는다.</strong> 0건을 거르던 조건이니 나오는 주문은 똑같다. 얻는 게 0이고 잃는 게 37초인 조건이었던 셈이다.</p><p>둘, <strong>추정치 1,648도 여전히 틀린 값이다.</strong> 실제는 36,120건이니 22배 낮다.<br>정확해진 게 아니라 병렬 임계값을 겨우 넘겼을 뿐이다. 이게 뒤에서 발목을 잡는다.</p><h3>기간을 줄였더니 다시 27초가 나왔다</h3><p>여기서 끝났으면 좋았을 텐데 더 재밌는게 남아 있었다.<br>지금 이 70ms는 워커가 붙어야 성립한다. 즉 옵티마이저가 heavy 하다고 판단되어야 워커가 붙는다.</p><p>워커 배정은 추정 페이지 수에 달려 있고, 추정 페이지 수는 조회 기간에 비례한다. 그래서 기간을 한 달에서 20일로 줄여봤다.</p><pre>Index Scan using idx_orders_closed on orders o<br>  (cost=0.56..4021.52 rows=1003) (actual ... rows=28211)    ← 추정 1,003<br>  actual time=1.9..455                                       ← 455ms, 인덱스는 멀쩡<br>(Workers Planned 줄 없음)                                    ← 워커 미배정<br>Sort  Sort Key: o.id DESC                                    ← 정렬이 다시 맨 위로<br>Index Scan using payments_pkey ...  loops=28211              ← 다시 2.8만 번</pre><p>26.9초.</p><p>기간을 좁혔더니 추정치가 1,503에서 1,003으로 떨어졌고, <strong>그게 병렬 임계값 아래였다</strong>. 워커가 안 붙으니 Gather Merge도 없고, orders만 먼저 정렬할 방법이 사라져서 정렬이 다시 꼭대기로 올라갔다. <strong>조인은 다시 2.8만 번이다</strong>.</p><p>병렬 임계값이 추정 1,003과 1,503 사이 어딘가에 있고, 그 선을 넘느냐 마느냐로 58배가 갈린다.</p><p>정리하면 이렇게 된다. <strong>데이터가 많으면 플래너가 “큰 작업이네” 하고 병렬을 붙이는데, 병렬이 붙으면 Gather Merge가 생기면서 정렬이 조인보다 먼저 오고, 그 덕에 조인이 20번으로 줄어 오히려 빨라진다.</strong> 반대로 데이터가 적으면 “작은 작업이네” 하고 병렬을 안 붙이고, 그러면 <strong>조인을 전부 돌아서 느려진다</strong>.</p><p>기간을 좁히면 플래너가 작은 쿼리라고 판단해 병렬을 포기하고,<br>병렬을 포기하면 정렬을 조인 아래로 내리는 경로가 사라지고, 결국 조인을 2.8만 번 돌게 된다.</p><p>성능이 데이터 양에 단조롭지 않으면 운영에서 예측이 안 된다.<br>“한 달치는 되는데 20일치는 안 돼요” 같은 제보가 들어오면 아무도 원인을 못 찾는다. 재현이 될 때도 있고 안 될 때도 있으니까. 임계값은 워커 여유(max_parallel_workers_per_gather)와 클러스터 부하에도 영향을 받으므로 같은 쿼리가 시간대에 따라 다르게 동작하기도 한다.</p><p>결국 조건을 지워서 얻은 70ms는 문제를 고친 게 아니라 <strong>플래너가 우연히 좋은 경로를</strong> 골라준 상태였다.</p><p><strong>여기까지는 원인을 밝히기 위한 실험이다.</strong> 조건을 지워서 70ms를 만든 건 “추정치가 이 모든 걸 좌우한다”는 걸 확인한 것이지 해결책이 아니다.</p><p>실제 운영 쿼리를 이렇게 플래너의 추정과 병렬 워커 배정에 맡겨두면, 조회 기간이 조금 바뀌거나 서버가 바쁜 시간대에 들어가는 것만으로 70ms가 27초가 된다. 되는 날과 안 되는 날이 갈리는 코드는 고친 게 아니다.</p><p>그래서 필요한 건 <strong>플래너가 어떤 판단을 하든 결과가 같은 쿼리</strong>다.</p><h3>풀려면 정렬을 인덱스에 맞춰야 한다</h3><p>문제의 핵심 원인은 인덱스가 ORDER BY o.id DESC를 제공하지 못한다는 것이다. 즉 LIMIT가 붙어 있어도 JOIN을 전부 돌고 난 뒤에야 정렬이 시작된다. 가장 확실한 해법은 정렬 키를 인덱스가 제공할 수 있는 순서로 바꾸는 것이다.</p><p>우리 인덱스는 (seller_id, store_id, closed_at)이다. 앞의 두 컬럼이 등호로 고정되면 closed_at은 이미 정렬된 순서로 나온다. 그러니 정렬 키를 closed_at으로 바꾸면 인덱스가 공짜로 순서를 준다.</p><pre>ORDER BY o.closed_at DESC   -- id DESC 대신<br><br>Limit 20<br> └ Nested Loop  loops=20<br>    └ Index Scan Backward using idx_orders_closed    ← Sort 노드 자체가 없음</pre><p>Sort 노드가 없으니 기다릴 것도 없다. 인덱스가 이미 정렬된 순서로 행을 흘려주고, 20건을 채우는 순간 스캔이 멈춘다. 조인이 20번인 건 물론이고, orders 2.8만 건을 읽을 필요조차 없다.</p><p>추정치가 몇이든 워커를 받든 못 받든 상관없다. 플래너의 판단이 개입할 여지 자체가 사라지기 때문이다.</p><p>인덱스 컬럼을 DESC로 다시 만들 필요도 없다. ASC 인덱스를 역방향으로 스캔하면 그대로 closed_at DESC가 나온다.</p><p>다만 이건 정렬 의미가 바뀌는 변경이라 기획 확인이 필요하다.<br>id DESC는 생성순이고 closed_at DESC는 마감순이라 대체로 같은 방향이지만 완전히 같지는 않다.</p><h3>정렬을 못 바꾼다면 — 서브쿼리로 조인을 막는다</h3><p>기획에서 반드시 등록 순서여야 한다고 하면 ORDER BY id DESC를 유지해야 한다면, orders를 전부 읽어서 정렬하는 건 피할 수 없다.</p><p>대신 조인 횟수만이라도 문법으로 고정할 수 있다. LIMIT을 서브쿼리 안에서 먼저 적용하고 그 결과에 조인하는 것이다.</p><pre>SELECT o.*, p.*, u.*, c.*<br>  FROM (<br>        SELECT * FROM orders<br>         WHERE seller_id = 1<br>           AND store_id  = 3<br>           AND closed_at &gt;= &#39;2026-07-01&#39;<br>           AND closed_at &lt;  &#39;2026-08-01&#39;<br>         ORDER BY id DESC<br>         LIMIT 20<br>       ) o<br>  LEFT JOIN payments p ON o.payment_id = p.id<br>  LEFT JOIN users    u ON o.user_id    = u.id<br>  LEFT JOIN codes    c ON o.status_key = c.key<br> ORDER BY o.id DESC;</pre><p>조인이 20건짜리 서브쿼리 결과 위에서만 일어난다. 추정치가 몇이든, 워커를 받든 못 받든, payments 조회는 항상 20번이다.</p><p>다만 orders를 전부 읽어서 정렬하는 비용은 그대로 남는다. 그리고 이건 디스크가 아니라 <strong>CPU를 쓰는 작업이다.</strong></p><p>3.6만 건을 정렬하면 그만큼 비교 연산이 돌고, work_mem도 그만큼 쓴다. 넘치면 디스크로 스필한다. 조회 기간이 5개월이면 24만 건이 되니 CPU 사용량도 그만큼 늘고, 목록 화면이라 사용자가 페이지를 넘길 때마다 매번 낸다.</p><p>물론 35초짜리 랜덤 I/O를 없앤 것에 비하면 훨씬 싸다. 70ms 수준이니 당장은 감당할 만하다. 하지만 공짜는 아니고, 동시 조회가 많아지면 DB CPU에서 보이기 시작한다. 이걸 없애려면 정렬 자체를 안 해야 한다.</p><h3>정리</h3><p>LIMIT n이 붙어 있어도 인덱스가 ORDER BY를 제공하지 못하면 조건에 맞는 행을 전부 읽고 전부 조인한다.</p><p>정렬은 마지막 행까지 봐야 순서를 확정할 수 있으니 조인이 전부 끝난 뒤에야 시작되고, Sort 밑에 조인이 있으면 조인 결과 전체가 Sort로 올라가야 하기 때문이다.</p><p>LIMIT은 정렬이 다 끝난 다음에야 일하니 그때는 이미 늦었다. top-N heapsort가 찍혀 있어도 마찬가지다. 보관할 행 수만 줄이지 읽을 행 수는 못 줄인다.</p><p>해법은 정렬을 인덱스가 제공할 수 있는 순서로 바꾸는 것이고,<br>그게 안 되면 서브쿼리에서 LIMIT을 먼저 적용해 조인 횟수만이라도 고정하는 것이다.</p><p>느린 쿼리를 만나면 인덱스보다 실행계획을 먼저 보자. loops가 수만인 노드가 있으면 그건 인덱스로 풀 문제가 아니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d3be1658ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DB 트랜잭션에서 UPDATE는 lock을 건다 — 따닥 버그 잡기]]></title>
            <link>https://medium.com/@letnaturebe2/db-%ED%8A%B8%EB%9E%9C%EC%9E%AD%EC%85%98%EC%97%90%EC%84%9C-update%EB%8A%94-lock%EC%9D%84-%EA%B1%B4%EB%8B%A4-%EB%94%B0%EB%8B%A5-%EB%B2%84%EA%B7%B8-%EC%9E%A1%EA%B8%B0-8137ee4a3366?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8137ee4a3366</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 10:21:51 GMT</pubDate>
            <atom:updated>2026-07-05T10:21:51.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-LJjSepxQlm6U_bA2AUsg.png" /></figure><p><a href="https://newvibot.com/ko">Slack 연차 관리 앱(vacay-buddy)</a>의 승인 코드를 들여다보다 race condition 하나를 발견했다. 실제로 장애가 발생한 적은 없었지만, 승인 버튼을 더블클릭하거나 Slack이 같은 요청을 재전송하면 코드상으로는 연차가 <strong>두 번 차감될 수 있었다</strong>. 흔히 말하는 “따닥”인데, 이걸 백엔드에서 막을 장치가 없었다.</p><p>이 글은 그 따닥을 <strong>트랜잭션 안에서 </strong><strong>UPDATE가 행에 lock을 건다</strong>는 컨셉으로 잡은 이야기다.</p><h3>기존 approve 코드</h3><p>먼저 승인이 어떤 흐름인지 보자.<br>연차는 승인자가 여러 명일 수 있어서, 승인은 체인으로 처리된다.<br>지금 승인자가 처리하면 다음 승인자에게 넘기고, <strong>마지막 승인자면 요청을 최종 승인 처리하고 그때 연차를 차감</strong>한다.</p><p>코드에 assert가 자주 나오는데, 별건 아니고 조건이 거짓이면 예외를 던지는 짧은 헬퍼다.</p><pre>function assert(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new Error(message);<br>}</pre><pre>@Transactional()<br>async approve(approver: User, approvalId: number, comment: string) {<br>  // ① 승인 정보를 읽어온다<br>  const approval = await this.getApproval(approvalId);<br>  // ② 아직 대기 상태인지 검사 (assert = 조건 실패 시 throw)<br>  assert(approval.status === PtoRequestStatus.Pending, &#39;This request has already been processed&#39;);<br>  // ③ 이 승인을 Approved로 바꾼다<br>  approval.status = PtoRequestStatus.Approved;<br>  const isFinalApproval = /* 내가 마지막 승인자인가 */;<br>  if (isFinalApproval) {<br>    approval.ptoRequest.status = PtoRequestStatus.Approved;<br>    // ④ 최종 승인이면 연차를 차감한다 (USAGE 잔액 insert)<br>    await this.ptoBalanceService.createPtoUsage(user, consumedDays, ptoRequest, ...);<br>  }<br>  await save(approval);<br>}</pre><p>createPtoUsage는 이름 그대로 &quot;사용&quot; 연차를 한 줄 <strong>insert</strong>하는 함수다.<br>즉 호출될 때마다 연차가 그만큼 깎인다.</p><pre>// pto-balance.service.ts (약식)<br>async createPtoUsage(user, amount, ...) {<br>  return this.createPtoBalance(user, -Math.abs(amount), USAGE, ...); // 사용은 항상 음수<br>}</pre><p>혼자 실행되면 완벽하다. 대기 상태인지 확인하고(②), 승인으로 바꾸고(③), 마지막이면 연차를 깎는다(④).</p><h3>왜 assert가 있는데도 뚫리나</h3><p>②에 assert가 있으니 두 번째 요청은 여기서 막힐 것 같다. 하지만 따닥으로 <strong>거의 동시에</strong> 두 요청이 들어오면 그렇지 않다.</p><pre>A: ① 읽음 → status = Pending<br>B: ① 읽음 → status = Pending   ← A가 아직 ③에 도달하지 못함<br>A: ② 통과 → ③ 승인 → ④ 연차 -1<br>B: ② 통과 → ③ 승인 → ④ 연차 -1   ← ❌ 또 깎인다</pre><p>핵심은 <strong>A와 B가 서로 다른 트랜잭션이고, </strong><strong>①의 읽기(</strong><strong>SELECT)는 아무 lock도 걸지 않는다</strong>는 것이다. 그래서 A가 상태를 바꾸기 전에 B도 똑같이 Pending을 읽어버린다.</p><p>둘 다 Pending을 봤으니 둘 다 assert를 통과하고, 둘 다 ④에 도달해 연차를 깎는다. assert는 자기가 읽은 값이 이미 유효하지 않다는 걸 알 방법이 없다.</p><p>(물론 운이 좋아서 B가 A보다 확실히 늦게 들어오면, B는 이미 Approved가 된 값을 읽어 assert에서 걸린다. 문제는 이게 <strong>타이밍에 달린 운</strong>이라는 점이다.)</p><p>정리하면 이전 코드의 문제는 이랬다.</p><blockquote><em>승인이 두 번 눌려 </em><em>③에서 </em><em>Approved로 두 번 </em><em>update되는 것 자체는 문제가 없다(같은 값을 두 번 쓸 뿐).</em></blockquote><blockquote><strong><em>진짜 문제는 </em></strong><strong><em>④의 연차 차감 insert가 두 번 실행되어, 실제로 연차가 두 번 깎이는 것</em></strong><em>이다.</em></blockquote><h3>풀려면 결국 locking이 필요하다</h3><p>이 틈(<strong>읽고 나서 쓰기까지의 사이</strong>)을 없애려면 결국 lock이 필요하다.<br>가장 직관적인 방법은 맨 위에서 승인 정보를 읽어올 때(getApproval) 아예 <strong>그 행에 lock을 잡고 읽는</strong> 것이다. <br>이른바 비관적 잠금(SELECT ... FOR UPDATE)이다.</p><pre>-- 약식 (join은 다 생략)<br>SELECT * FROM pto_approval WHERE id = ? FOR UPDATE;</pre><p>FOR UPDATE로 읽으면 그 행에 배타적 lock이 걸린다. A가 이 lock을 쥐고 있는 동안 B의 SELECT ... FOR UPDATE는 <strong>대기</strong>한다. A가 트랜잭션을 커밋해 lock을 놓으면, 그제서야 B가 읽는데 이때는 이미 Approved이므로 ② assert에서 걸린다. 틈이 사라진다.</p><p>이 방법도 맞다. 다만 TypeORM에서 lock 모드를 지정해 읽도록 조회 코드를 손봐야 하고, “여기서는 lock을 잡고 읽는다”는 사실이 조회 함수에 숨는다.</p><h3>더 간단한 방법 — UPDATE의 위치만 바꾼다</h3><p>별도의 FOR UPDATE 없이, 이미 있는 코드의 <strong>UPDATE 위치만 바꿔서</strong> 같은 효과를 낼 수 있다. 두 가지 사실을 엮으면 된다.</p><ol><li>approve에는 @Transactional()이 붙어 있다 → 이 함수 전체가 하나의 트랜잭션으로 열린다.</li><li><strong>트랜잭션 안에서 </strong><strong>UPDATE를 실행하면, 그 행에 배타적 lock(exclusive lock)이 걸리고 트랜잭션이 끝날 때까지 유지된다.</strong> 같은 행을 UPDATE하려는 다른 트랜잭션은 그때까지 대기한다.</li></ol><p>즉 UPDATE는 단순한 쓰기가 아니라 &quot;이 행을 내가 선점한다&quot;는 lock 행위를 겸한다. 그렇다면 <strong>검사도 이 </strong><strong>UPDATE에 실어버리면</strong> 된다.</p><p>SELECT로 읽고 → 코드에서 판단하고 → 나중에 UPDATE하는 대신, 조건을 WHERE에 넣은 UPDATE 한 방으로 &quot;대기 상태인지 검사&quot;와 &quot;선점&quot;을 원자적으로 합치는 것이다.</p><pre>UPDATE pto_approval<br>   SET status = &#39;approved&#39;<br> WHERE id = ? AND status = &#39;pending&#39;;   -- 검사 조건(pending)이 WHERE로 내려간다</pre><p>이 쿼리는 DB 안에서 원자적으로 돈다. 그리고 몇 행이 바뀌었는지affected 확인한다.</p><ul><li>affected === 1 → 내가 pending을 선점했다. 계속 진행.</li><li>affected === 0 → 다른 트랜잭션이 이미 바꿨다(더는 pending이 아니다). 중단.</li></ul><p>수정한 코드는 이렇다. 로직을 새로 짠 게 아니라, <strong>UPDATE를 앞으로 당기고 검사를 거기에 실은 것</strong>뿐이다.</p><pre>@Transactional()<br>async approve(approver: User, approvalId: number, comment: string) {<br>  const approval = await this.getApproval(approvalId);<br>  this.validatePendingApproval(approver, approval); // 권한 검사 등 빠른 실패용<br>  <br>  // pending일 때만 원자적으로 선점 - 검사와 상태 변경을 UPDATE 한 번으로 합친다<br>  const claim = await ptoApprovalRepository.update(<br>    { id: approvalId, status: PtoRequestStatus.Pending }, // WHERE: 검사 조건(status=pending)을 여기에 실었다<br>    { status: PtoRequestStatus.Approved, comment, actionDate: new Date() },<br>  );<br><br>  assert(claim.affected === 1, &#39;This request has already been processed&#39;);<br>  // 여기부터는 race condition이 보장된다. 이제서야 연차를 차감한다.<br>  if (isFinalApproval) {<br>    await this.ptoBalanceService.createPtoUsage(user, consumedDays, ptoRequest, ...);<br>  }<br>  await save(ptoRequest);<br>}</pre><p>이제 A와 B가 동시에 들어와도 이렇게 흘러간다.</p><pre>A: UPDATE ... WHERE status=&#39;pending&#39;  → 행을 잠그고 pending→approved<br>B: UPDATE ... WHERE status=&#39;pending&#39;  → A의 lock이 풀릴 때까지 대기(블록)<br>A: COMMIT                             → lock 해제, affected = 1 (승자)<br>B: 대기 풀림 → 그런데 status는 이미 &#39;approved&#39;<br>                                     → WHERE에 걸리는 행이 없음 → affected = 0 (패자)</pre><p>B는 A가 끝날 때까지 <strong>강제로 기다렸다가, 갱신된 최신 상태 위에서 다시 판정</strong>한다. B가 보는 값은 더 이상 낡지 않았다.</p><p>그리고 affected === 0 → assert에서 기존과 똑같은 &quot;already been processed&quot; 에러로 멈춘다. 무엇보다 <strong>연차 차감(</strong><strong>createPtoUsage)은 선점에 성공한 승자만 도달</strong>하므로, 이중 차감이 원천적으로 사라진다.</p><p>핵심은 부수효과(연차 차감)보다 <strong>lock 선점을 먼저</strong> 두었다는 것이다. 진 요청은 차감 코드에 닿지도 못한다.</p><blockquote><em>참고로 </em><em>UPDATE 앞에 </em><em>validatePendingApproval을 여전히 남겨뒀다. <br>권한이 없거나 명백히 처리된 요청 같은 &quot;정상적인 대부분의 실패&quot;는 굳이 lock을 잡기 전에 앞에서 싸게 걸러내는 게 낫다.</em></blockquote><h3>정리</h3><p>read-then-write 사이의 틈이 따닥 버그(race condition)의 본질이다.<br>애플리케이션의 if/assert로는 그 틈을 없앨 수 없다 <br>(검사하는 값이 이미 낡았기 때문이다.)</p><p>해법은 의외로 단순하다. @Transactional() 안에서 <strong>UPDATE가 행에 exclusive lock을 건다</strong>는 성질을 이용해, 검사 조건을 WHERE로 내려 검사와 선점을 하나의 원자적 연산으로 합치고(affected로 승패 판정), 부수효과는 선점에 성공한 뒤로 미루는 것이다.</p><p>SELECT ... FOR UPDATE로 명시적 lock을 잡아도 되지만, 이미 쓰던 UPDATE의 순서를 바꾸는 것만으로도 충분했다.</p><p>한 가지 주의할 점. UPDATE가 잡은 lock은 <strong>트랜잭션이 끝날 때(커밋/롤백)까지 계속 유지</strong>된다. 그동안 같은 행을 건드리려는 다른 트랜잭션은 전부 대기하므로, lock을 잡은 뒤의 트랜잭션은 <strong>최대한 빨리 끝내는 게 좋다.</strong></p><p>무거운 외부 호출이나 오래 걸리는 작업을 lock 잡은 채로 물고 있으면 그만큼 남들이 줄 서서 기다린다. DELETE도 UPDATE와 똑같이 행에 exclusive lock을 걸므로 같은 원리가 적용된다.</p><p>동시성 방어의 마지막 보루는 애플리케이션이 아니라 DB에 두는 게 안전하다. 데이터 정합성을 최종적으로 책임지는 곳은 결국 DB이기 때문이다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8137ee4a3366" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[백엔드 개발자가 htmx로 프론트를 걷어낸 이야기]]></title>
            <link>https://medium.com/@letnaturebe2/%EB%B0%B1%EC%97%94%EB%93%9C-%EA%B0%9C%EB%B0%9C%EC%9E%90%EA%B0%80-htmx%EB%A1%9C-%ED%94%84%EB%A1%A0%ED%8A%B8%EB%A5%BC-%EA%B1%B7%EC%96%B4%EB%82%B8-%EC%9D%B4%EC%95%BC%EA%B8%B0-82f985c08896?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f985c08896</guid>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 02:55:51 GMT</pubDate>
            <atom:updated>2026-06-28T02:55:51.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbKCt7Cgqz1jT8BNo4xW4w.png" /></figure><p>저는 백엔드 개발자라 프론트엔드에는 능숙하지 않습니다. 그래서<a href="https://newvibot.com/ko"> Slack 연차·근태 관리 앱(vacay-buddy)</a>을 만들 때도 Express + TypeScript에 EJS로 서버사이드 렌더링(SSR)을 하고, 거기에 jQuery를 얹는 구성을 택했습니다.</p><p>React 같은 SPA 프레임워크는 쓰지 않았는데, 이 정도 규모에서는 서버가 HTML을 직접 그려 내려주는 편이 더 단순하고 효율적이라고 판단했기 때문입니다.</p><p>문제는 SSR을 한다면서도 정작 데이터는 클라이언트가 다시 그리고 있었다는 점입니다. EJS로는 페이지 뼈대만 그리고, 실제 목록·상태는 jQuery가 fetch → innerHTML로 채우는 식이었습니다. 게다가 그 프론트엔드 코드는 주로 AI에게 맡겨 작성하다 보니 화면마다 패턴이 제각각이었고, fetch·innerHTML·location.reload()가 쌓이면서 점점 손대기 어려운 덩어리가 되어 갔습니다. 화면 하나를 고치려면 서버 템플릿과 클라이언트 렌더 두 곳을 같이 손봐야 했습니다.</p><p>그래서 목표는 단순했습니다. <strong>프론트엔드 코드의 양 자체를 최대한 줄이는 것</strong>입니다. 그 수단으로 htmx를 골랐습니다. 관통하는 원칙은 하나입니다 — <strong>화면 상태의 단일 진실 공급원(Single Source of Truth)은 언제나 서버다.</strong> 클라이언트가 별도의 상태를 들고 화면을 다시 그리는 게 아니라, 서버가 그린 HTML 조각이 곧 화면이고, 클라이언트는 그걸 “어디에 끼울지”만 선언합니다.</p><p>선택에는 한 가지 이유가 더 있었습니다. 앞으로도 프론트엔드는 AI에게 맡길 생각인데, 그러면 <strong>사람이 일일이 검토하지 않은 코드가 계속 들어온다</strong>는 뜻입니다. 회귀를 막으려면 테스트가 필수인데, 클라이언트가 렌더하는 코드는 테스트가 비쌉니다(브라우저나 jsdom이 필요합니다). 반면 서버가 HTML을 반환하면 <strong>API를 호출해 그 HTML이 제대로 나오는지만 검증하면 됩니다.</strong></p><p>즉 htmx로 옮기면 “코드가 줄어드는 것”과 “테스트가 싸지는 것”이 함께 따라옵니다. 실제로 이 전환 뒤 라우트 테스트를 대거 깔 수 있었습니다.</p><p>이 글은 그 포팅 과정의 기록입니다.<br>왜 바꿨는지(1장), htmx가 무엇을 해주는지(2장), 왜 테스트가 쉬워졌는지(3장), 그리고 실제 화면들을 어떻게 옮겼는지(4장)를 다룹니다.</p><blockquote><em>환경: Node + Express + TypeScript + EJS + TypeORM. SPA 프레임워크 없이 SSR + jQuery 구성이었고, 새로 추가한 라이브러리는 htmx 하나뿐입니다.</em></blockquote><h3>1. 페인 포인트 — 왜 바꿨나</h3><p>데이터를 받아 화면을 그리는 코드가 곳곳에 이런 식으로 깔려 있었습니다.</p><pre>const res = await fetch(&#39;/api/teams?token=&#39; + token);<br>const data = await res.json();<br>teamsList.innerHTML = data.teams.map(t =&gt; `&lt;div&gt;...${t.name}...&lt;/div&gt;`).join(&#39;&#39;);</pre><p>이건 그나마 순한 편입니다. 더 흔한 건 <strong>토글 하나가 화면 여러 곳을 조건부로 바꾸는</strong> 코드였습니다.</p><p>예를 들어 관리자 권한 토글 하나가 <br>(1) 배지 텍스트, (2) 옆의 “연차 수정” 토글의 체크/비활성/툴팁, (3) “관리자가 1명만 남으면 그 토글을 잠그는” 다른 행들의 상태까지 바뀌어야 했고, 이 모든 분기가 프론트 코드에 얽혀 있었습니다.</p><p>아래와 같은 코드 패턴은 AI가 실수하기 쉽고 테스트하기도 까다로워 기술부채로 남겠다는 생각을 했습니다.</p><pre>async function toggleAdminStatus(userId, isAdmin) {<br>  const res = await fetch(&#39;/api/update-admin-status&#39;, {<br>    method: &#39;POST&#39;, headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify({ token, targetUserId: userId, isAdmin }),<br>  });<br>  const data = await res.json();<br>  if (!data.success) {<br>    $(`input[data-user-id=&quot;${userId}&quot;]`).prop(&#39;checked&#39;, !isAdmin); // 실패 → 체크 되돌리기<br>    return showToast(data.message, &#39;error&#39;);<br>  }<br>  // (1) 배지 교체<br>  const badge = $(`#badge-${userId}`);<br>  badge.toggleClass(&#39;active&#39;, isAdmin).toggleClass(&#39;inactive&#39;, !isAdmin)<br>       .html(isAdmin ? &#39;&lt;i class=&quot;fas fa-shield-alt&quot;&gt;&lt;/i&gt; 관리자&#39; : &#39;&lt;i class=&quot;fas fa-user&quot;&gt;&lt;/i&gt; 일반&#39;);<br>  // (2) 옆 &quot;연차 수정&quot; 토글의 checked/disabled/title을 새 상태에 맞춰 다시 계산<br>  const editInput = document.querySelector(`.pto-edit-cell[data-user-id=&quot;${userId}&quot;] .pto-edit-input`);<br>  if (editInput) {<br>    editInput.checked = isAdmin;<br>    editInput.disabled = !(currentUserIsSuperAdmin &amp;&amp; isAdmin);<br>    // ...title도 조건에 따라 set/remove...<br>  }<br>  // (3) 관리자 수에 따라 &quot;다른 행들&quot;의 토글까지 다시 훑어 잠그거나 푼다<br>  updateAdminToggles();<br>}</pre><p>정리하자면 아래와 같은 문제가 발생했습니다.</p><ul><li><strong>명령형 DOM 조작이 범람합니다.</strong> 상태가 바뀔 때마다 “화면의 어디를, 어떻게 바꿀지”를 클라이언트가 일일이 수정합니다. 조건이 하나 늘면 분기가 하나 늘고, 금세 읽기 어려운 덩어리가 됩니다. 사실 이 “명령형 DOM 조작의 피로”를 덜기 위해 나온 것이 React 같은 선언형 UI 프레임워크입니다. UI = f(state)로 선언하면 실제 DOM 갱신은 프레임워크가 맡아 줍니다.</li><li><strong>서버와 클라이언트의 상태가 어긋납니다. </strong>첫 화면은 서버가 그려 주지만, 이후 변경은 클라이언트가 자기가 따로 들고 있는 데이터로 화면을 다시 그립니다. 같은 정보를 양쪽이 각자 관리하는 셈이라, 둘의 sync가 깨지는 순간 화면이 실제 데이터와 어긋나는 버그(stale)가 됩니다.</li><li><strong>테스트가 어렵습니다.</strong> 프론트 로직이 브라우저 DOM에 의존하므로 이jsdom이나 E2E 없이는 검증하기 힘들고, 그래서 사실상 작성하지 않게 됩니다.</li></ul><p>업데이트나 삭제가 일어났을 때, 분기를 일일이 짜기 싫으면 그냥 reload로 때우기도 했습니다. “저장되었습니다” 토스트를 띄우고 2초 뒤에 페이지를 새로고침하는 식이죠. 유저 입장에선 깜빡임이 따라오니 좋은 경험은 아닙니다. 이 부분도 htmx가 굉장히 편하게 해결해 줍니다.</p><p><strong>htmx의 발상은 되게 심플합니다.<br>백엔드가 로직을 처리한 다음 바뀐 UI(HTML)까지 한 번에 돌려주면</strong> 클라이언트가 DOM을 만질 일이 없어진다.</p><h3>2. htmx로 무엇을 하나 — 같은 기능, 프론트 코드는 1/10</h3><blockquote><em>서버가 HTML 조각을 렌더해서 내려주고, htmx가 그것을 지정한 자리에 끼워 넣습니다.</em></blockquote><p>“팀 삭제 후 목록 갱신”이라는 흔한 동작 하나를 전후로 비교해 보겠습니다.</p><p><strong>Before — 클라이언트가 전부 처리 (버튼 + JS 핸들러)</strong></p><pre>// 1) 버튼에 onclick, 2) 핸들러에서 fetch, 3) JSON 파싱, 4) 성공/실패 분기,<br>//    5) DOM에서 행을 찾아 지우거나 location.reload(), 6) 에러 토스트...<br>async function deleteTeam(id) {<br>  if (!confirm(&#39;삭제할까요?&#39;)) return;<br>  try {<br>    const res = await fetch(`/api/teams/${id}?token=${getToken()}`, { method: &#39;DELETE&#39; });<br>    const data = await res.json();<br>    if (!data.success) { showToast(data.message, &#39;error&#39;); return; }<br>    document.querySelector(`#team-${id}`).remove();   // 또는 location.reload()<br>    updateTeamCount();                                // 카운트도 따로 갱신<br>    showToast(&#39;삭제되었습니다&#39;);<br>  } catch (e) {<br>    showToast(&#39;오류가 발생했습니다&#39;, &#39;error&#39;);<br>  }<br>}</pre><p><strong>After — 버튼이 곧 선언, 클라이언트 JS 0줄</strong></p><pre>&lt;button hx-delete=&quot;/teams/3?token=...&quot;<br>        hx-target=&quot;#teams-list&quot; hx-swap=&quot;outerHTML&quot;<br>        hx-confirm=&quot;삭제할까요?&quot;&gt;삭제&lt;/button&gt;</pre><pre>// 서버: 삭제 후 &quot;갱신된 목록 HTML&quot;을 그대로 반환 → htmx가 #teams-list에 끼웁니다.<br>app.delete(&#39;/teams/:id&#39;, async (req, res) =&gt; {<br>  await teamService.deleteTeam(id);<br>  const teams = await teamService.getTeams(org);<br>  res.render(&#39;partials/hx/settings-team-list&#39;, { teams });   // HTML 조각을 client에 반환<br>});</pre><p>htmx가 자동으로 대신 처리해 주는 것은 다음과 같습니다. 그래서 위의 JS가 통째로 사라집니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISFiO8-Hbe34gIBouWk7zA.png" /></figure><p>요청·파싱·DOM 삽입·에러 처리 같은 AJAX 보일러플레이트를 htmx가 가져가고, 개발자는 “어디에(hx-target) / 무엇을(hx-get/hx-post 등)&quot; 두 가지만 선언하면 됩니다. 핸들러 함수 하나가 속성 서너 개로 줄어듭니다.</p><h3>3. 덤: 테스트가 거의 공짜로 따라온다</h3><p>프론트 코드를 AI에 많이 맡기는 만큼, 개인적으로 가장 마음에 들었던 점은 테스트가 쉬워진다는 것이었습니다. 테스트라는 안전망이 있으면 <strong>AI가 그 테스트를 깨지 않는 선에서 코드를 넣게 되므로</strong>, 안심하고 작업을 맡길 수 있습니다. 마침 서버가 HTML 문자열을 반환하니, HTTP 요청을 한 번 보내고 그 문자열만 검증하면 됩니다. 브라우저도 jsdom도 필요 없습니다.</p><pre>// 실제로 들어간 테스트 (supertest)<br>it(&#39;DELETE /teams/:id → 삭제 후 목록 조각에서 빠짐&#39;, async () =&gt; {<br>  const { organization, token } = await makeAdmin();<br>  const keep = await teamService.createTeam(&#39;남는팀&#39;, organization);<br>  const remove = await teamService.createTeam(&#39;지울팀&#39;, organization);<br>  const res = await request(app).delete(`/teams/${remove.id}?token=${encodeURIComponent(token)}`);<br>  <br>  expect(res.status).toBe(200);<br>  expect(res.text).toContain(&#39;id=&quot;teams-list&quot;&#39;);<br>  expect(res.text).toContain(&#39;남는팀&#39;);<br>  expect(res.text).not.toContain(&#39;지울팀&#39;);<br>});</pre><ul><li><strong>Before(클라이언트 렌더):</strong> renderTeams()가 브라우저 DOM에 그리므로 Playwright나 jsdom 같은 무거운 E2E가 필요하고, 결국 작성하지 않게 됩니다.</li><li><strong>After(서버 렌더):</strong> 라우트를 호출하고 응답 HTML을 검증하면 됩니다. 그냥 단위 테스트입니다.</li></ul><p>라우트별로 테스트를 충분히 작성해 커버했고, 이 테스트들이 이후 리팩터링의 안전망이 됩니다.</p><blockquote><em>다만 클릭하면 사이드바가 토글되는 식의 “순수 인터랙션”은 여전히 클라이언트 JS이므로 supertest로는 볼 수 없습니다. supertest가 검증하는 범위는 “엔드포인트가 올바른 HTML을 주는가”까지입니다.</em></blockquote><h3>4. 대표 적용 예시</h3><p>이제부터는 실제 화면을 하나씩 htmx로 옮기면서 프론트 코드가 어떻게 줄었는지 보여드리겠습니다. 화면마다 형태는 달라도 발상은 같습니다 — <strong>프론트가 하던 액션(fetch·DOM 조작)은 htmx 속성으로 대체하고, 그 자리에 그리던 화면은 서버가 반환한 응답으로 대체하는 것</strong>입니다. 반복적으로 쓰인 패턴들을 차례로 살펴봅니다.</p><h3>4–1. OOB로 한 번에 세 곳 갱신 — 연차 부여</h3><p>관리자가 “추가 연차 부여” 모달에서 일수를 입력하고 확인을 누르면,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TVhk2U6FzxpQGuHrB53RA.png" /></figure><p>직원 상세 화면의 세 곳이 바뀌어야 합니다. <br>(1) 아래의 잔여 이력 테이블, (2) 상단 “남은 연차 / 올해 사용한 연차” 요약 카드, (3) (목록 화면의) 왼쪽 직원 리스트의 “N일 남음”입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScMwhO4Ak7NAylW5ksU_ug.png" /></figure><p>아래가 그 기존 코드입니다. 프론트에서 서버로 요청을 보낸 뒤, 응답을 받아 UI와 모달을 직접 갱신했습니다. AI가 잘 짜 주긴 했지만, 화면 상태의 기준(SSOT)이 클라이언트 곳곳에 흩어져 있다 보니 갱신할 곳이 늘수록 한두 군데를 빠뜨리기 쉬운 구조였습니다. <br>그래서 이 화면은 htmx로 옮기면서 <strong>서버가 바뀐 조각을 한 번에 내려주도록</strong> 바꿨습니다.</p><p><strong>Before — 서버 전송 + 세 곳을 따로따로 갱신:</strong></p><pre>async function submitGrant() {<br>  const amount = parseFloat(document.getElementById(&#39;grantAmount&#39;).value);<br>  const date = document.getElementById(&#39;grantDate&#39;).value;<br>  // ...만료일·메모 읽기 + 빈 값 검증 (생략)...<br>  const res = await fetch(&#39;/api/admin-pto-adjustment&#39;, {<br>    method: &#39;POST&#39;, headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify({ token, userId: selectedEmployeeId, amount, effectiveDate: date, memo }),<br>  });<br>  const data = await res.json();<br>  if (!data.success) return showToast(data.message, &#39;error&#39;);<br>  showToast(&#39;연차 부여가 완료되었습니다.&#39;, &#39;success&#39;);<br>  closeGrantDialog();<br>  updatePtoSummary(data.updatedPtoSummary);   // (2) 요약 카드 patch<br>  loadBalanceHistory(selectedEmployeeId);      // (1) 이력 테이블 재조회·재렌더<br>  // (3) 왼쪽 리스트 &quot;N일 남음&quot;은 또 따로 갱신…<br>}<br>function updatePtoSummary(s) {<br>  document.querySelector(&#39;.summary-item.used .summary-value&#39;).textContent = s.usedPtoDisplay;<br>  document.querySelector(&#39;.summary-item.remaining .summary-value&#39;).textContent = s.remainingPtoDisplay;<br>}</pre><p>세 곳을 각각 다른 방식(요약은 textContent, 테이블은 재조회·재렌더, 리스트는 또 따로)으로 갱신하다 보니 하나라도 빼먹으면 화면이 어긋났습니다. 지금은 서버 조각 하나가 모두 해결합니다.</p><p>이때 쓰는 것이 <strong>OOB(Out Of Band) swap</strong>입니다.<br>htmx는 응답을 기본적으로 hx-target 한 곳에만 넣지만, 응답 HTML의 어떤 엘리먼트에 hx-swap-oob=&quot;true&quot;를 붙이면 그것을 타겟이 아니라 <strong>id가 같은 기존 요소에 따로</strong> 갈아끼웁니다.<br>덕분에 서버 조각 하나로 여러 곳을 동시에 갱신할 수 있습니다.</p><p><strong>After — 서버 조각</strong> (partials/hx/admin-employee-balance-fragment.ejs)</p><pre>// (1)메인 타깃(#balanceTableBody): 잔여 이력 테이블 전체를 새 데이터로 다시 그려 refresh.<br>// hx-target이 #balanceTableBody라 부여 1건이 새 행으로 추가된 모습.<br>&lt;%- include(&#39;./pto-balance-rows&#39;, { balances, formatDaysAndHours }) %&gt;<br><br>// (2) OOB: 상단 요약 카드. 타깃 밖이지만 id(summaryRemaining/summaryUsed)가 같은<br>//     기존 요소를 찾아 &quot;남은 연차 / 올해 사용한 연차&quot; 숫자만 따로 교체.<br>&lt;div class=&quot;summary-value&quot; id=&quot;summaryRemaining&quot; hx-swap-oob=&quot;true&quot;&gt;&lt;%= formatDaysAndHours(targetUser.remainingPtoDays) %&gt;&lt;/div&gt;<br>&lt;div class=&quot;summary-value&quot; id=&quot;summaryUsed&quot;      hx-swap-oob=&quot;true&quot;&gt;&lt;%= formatDaysAndHours(targetUser.usedPtoDays) %&gt;&lt;/div&gt;<br>// (3) OOB: 목록 화면 왼쪽 직원 리스트의 &quot;N일 남음&quot; 배지. 같은 유저 id의 요소를 찾아 갱신.<br>&lt;span class=&quot;pto-remaining&quot; id=&quot;pto-remaining-&lt;%= targetUser.userId %&gt;&quot; hx-swap-oob=&quot;true&quot;&gt;&lt;%= formatDaysAndHours(targetUser.remainingPtoDays) %&gt; 남음&lt;/span&gt;</pre><p><strong>서버 라우트</strong> (부여·차감·조정 삭제가 전부 이 조각 하나를 반환)</p><pre>app.post(&#39;/api/admin-pto-adjustment&#39;, async (req, res) =&gt; {<br>  await ptoBalanceService.createManualAdjustment(targetUser, amount, ...);<br>  const updatedUser = await userService.getUser(targetUserId);<br>  const balances = await ptoBalanceService.getPtoBalanceTable(updatedUser);<br>  // 잔여 테이블 + 요약 + 왼쪽 리스트가 이 한 응답으로 모두 갱신됩니다.<br>  res.render(&#39;partials/hx/admin-employee-balance-fragment&#39;,<br>             { balances, targetUser: updatedUser, formatDaysAndHours });<br>});</pre><p><strong>클라이언트(폼)</strong> — 선언형, JS 0줄</p><pre>&lt;form hx-post=&quot;/api/admin-pto-adjustment&quot; hx-target=&quot;#balanceTableBody&quot; hx-swap=&quot;innerHTML&quot;<br>      hx-on::after-request=&quot;if(event.detail.successful){ closeGrantDialog(); }&quot;&gt;<br>  &lt;input type=&quot;hidden&quot; name=&quot;userId&quot; value=&quot;...&quot;&gt;<br>  &lt;input name=&quot;amount&quot;&gt; &lt;input name=&quot;effectiveDate&quot; type=&quot;date&quot;&gt; ...<br>  &lt;button type=&quot;submit&quot;&gt;부여&lt;/button&gt;<br>&lt;/form&gt;</pre><blockquote><em>프론트엔드 코드는 정말 0줄입니다. “부여” 버튼을 누르면 서버가 처리 후 </em><strong><em>세 곳을 한 번에 갱신</em></strong><em>합니다. JS로 직접 갱신하던 코드가 통째로 사라졌습니다.</em></blockquote><p>여기에 테스트를 한 줄 더 깔아 둡니다. 응답 HTML과 실제 DB 상태를 같이 검증해 두면, 앞으로 AI가 이 화면을 다시 손대도 “부여하면 요약이 갱신되고 잔여가 실제로 생긴다”는 보장이 깨지는 순간 테스트가 잡아 줍니다 — 안정성을 미리 주입해 두는 셈입니다.</p><pre>it(&#39;POST /api/admin-pto-adjustment (HX) → 잔여 패널 조각 반환 + 실제 부여&#39;, async () =&gt; {<br>  const { member, token } = await setup();<br>  const res = await request(app)<br>    .post(&#39;/api/admin-pto-adjustment&#39;).set(&#39;HX-Request&#39;, &#39;true&#39;).type(&#39;form&#39;)<br>    .send({ token, userId: member.userId, amount: &#39;3&#39;, effectiveDate: &#39;2026-06-01&#39;, memo: &#39;특별 부여&#39; });<br>  <br>  expect(res.status).toBe(200);<br>  expect(res.text).toContain(&#39;id=&quot;summaryRemaining&quot;&#39;); // OOB 요약 갱신 포함<br>  expect(res.text).toContain(&#39;특별 부여&#39;);               // 부여 메모가 잔여 행에 보임<br>  const balances = await ptoBalanceService.getPtoBalanceTable(member); // 도메인 교차 검증<br>  expect(balances.length).toBeGreaterThan(0);<br>});</pre><h3>4–2. 설정 토글·라디오 — jQuery 걷어내기</h3><p>두 번째는 토글·라디오에서 jQuery를 걷어낸 예시입니다. 설정 화면에는 이런 컨트롤이 잔뜩 있었는데, 전부 jQuery가 값이 바뀔 때마다 API를 호출하고 그 응답으로 화면을 다시 그리고 있었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSM41UWSHzU-3Xn9CgAFiA.png" /></figure><p>이걸 전부 “변경 → 서버가 새 상태의 조각을 렌더해 반환”으로 바꿨습니다(SSOT). 클라이언트 코드가 사라져 코드량이 크게 줄었고, “저장되었습니다” 토스트도 서버가 응답에 실어 보냅니다(4–3).</p><p>대표 사례는 “일일 휴가 공지 활성화” 토글입니다. “활성화” 하나가 시간 선택과 테스트 버튼의 disabled 상태까지 좌우하는 종속 UI입니다.</p><p><strong>Before (jQuery + fetch + 함수 2개 + 로드 초기화):</strong></p><pre>async function updateDailyPtoAnnouncementEnabled(enabled) {<br>  const res = await fetch(&#39;/api/...enabled&#39;, { method:&#39;POST&#39;, body: JSON.stringify({token, enabled}) });<br>  const data = await res.json();<br>  if (data.success) { showToast(...); toggleDailyAnnouncementControls(enabled); }<br>  else { $(&#39;#daily-pto-announcement-enabled&#39;).prop(&#39;checked&#39;, !enabled); }   // 실패 시 롤백<br>}<br>function toggleDailyAnnouncementControls(enabled) {      // 종속 컨트롤 회색 처리/disabled<br>  controls.style.opacity = enabled ? &#39;1&#39; : &#39;0.5&#39;; timeSelect.disabled = !enabled; testBtn.disabled = !enabled;<br>}<br>$(document).ready(() =&gt; toggleDailyAnnouncementControls(&lt;%- &#39;initial&#39; %&gt;));   // 로드 시 초기 상태도 JS로</pre><p><strong>After.</strong> 섹션 본문을 EJS 조각으로 만들고, enabled 상태에 따라 컨트롤의 disabled까지 <strong>서버가</strong> 그립니다(settings-daily-announcement.ejs).</p><pre>&lt;div id=&quot;daily-announcement-body&quot;&gt;<br>  &lt;input type=&quot;checkbox&quot; name=&quot;enabled&quot; &lt;%= enabled ? &#39;checked&#39; : &#39;&#39; %&gt;<br>         hx-post=&quot;/api/update-daily-pto-announcement-enabled&quot; hx-trigger=&quot;change&quot;<br>         hx-target=&quot;#daily-announcement-body&quot; hx-swap=&quot;outerHTML&quot;&gt;<br>  &lt;%# 종속 컨트롤의 활성/비활성을 서버가 enabled로 결정 %&gt;<br>  &lt;select &lt;%= enabled ? &#39;&#39; : &#39;disabled&#39; %&gt; ...&gt; ... &lt;/select&gt;<br>  &lt;button &lt;%= enabled ? &#39;&#39; : &#39;disabled&#39; %&gt;&gt;테스트 발송&lt;/button&gt;<br>&lt;/div&gt;</pre><p>라우트는 저장한 뒤 <strong>그 조각을 그대로 다시 렌더해 반환</strong>합니다.</p><pre>app.post(&#39;/api/update-daily-pto-announcement-enabled&#39;, async (req, res) =&gt; {<br>  const enabled = await saveAnnouncementEnabled(req);                 // 저장<br>  hxToast(res, enabled ? &#39;활성화되었습니다.&#39; : &#39;비활성화되었습니다.&#39;);  // &quot;저장되었습니다&quot; 토스트<br>  res.render(&#39;partials/hx/settings-daily-announcement&#39;, { organization, token });<br>});</pre><p>결과적으로 프론트 코드가 전부 삭제되었습니다. 시간 선택과 테스트 버튼의 disabled, 토글 체크 상태까지 전부 서버가 그린 HTML 그대로이므로 프론트에서 상태 변경 코드가 없습니다.</p><p>라디오도 똑같습니다. “연차 승인 모드(수동/자동)”는 라디오를 누르면 <strong>선택 표시(</strong><strong>active 클래스)를 클라가 직접 옮기고</strong> fetch로 저장했습니다.</p><p><strong>Before (jQuery로 선택 표시 이동 + fetch):</strong></p><pre>async function updateApprovalMode(approvalMode) {<br>  // 선택 표시를 클라가 직접 떼고 붙인다<br>  $(&#39;input[name=&quot;approvalMode&quot;]&#39;).closest(&#39;.permission-option&#39;).removeClass(&#39;active&#39;);<br>  $(`input[name=&quot;approvalMode&quot;][value=&quot;${approvalMode}&quot;]`).closest(&#39;.permission-option&#39;).addClass(&#39;active&#39;);<br>  const res = await fetch(&#39;/api/update-approval-mode&#39;, {<br>    method: &#39;POST&#39;, headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify({ token, approvalMode }),<br>  });<br>  const data = await res.json();<br>  showToast(data.success ? &#39;승인 모드가 업데이트되었습니다&#39; : data.message, data.success ? &#39;info&#39; : &#39;error&#39;);<br>}<br>// 마크업: &lt;input type=&quot;radio&quot; ... onchange=&quot;updateApprovalMode(this.value)&quot;&gt;</pre><p><strong>After (</strong><strong>settings-approval-mode.ejs) — </strong><strong>checked를 서버가 그리고 JS는 0줄:</strong></p><pre>&lt;div class=&quot;permission-options&quot; id=&quot;approval-mode-options&quot;&gt;<br>  &lt;label class=&quot;permission-option&quot;&gt;<br>    &lt;input type=&quot;radio&quot; name=&quot;approvalMode&quot; value=&quot;&lt;%= ApprovalMode.AUTO %&gt;&quot;<br>           &lt;%= organization.approvalMode === ApprovalMode.AUTO ? &#39;checked&#39; : &#39;&#39; %&gt;<br>           hx-post=&quot;/api/update-approval-mode&quot; hx-trigger=&quot;change&quot;<br>           hx-vals=&#39;{&quot;token&quot;:&quot;&lt;%= token %&gt;&quot;}&#39;<br>           hx-target=&quot;#approval-mode-options&quot; hx-swap=&quot;outerHTML&quot;&gt;<br>    &lt;span&gt;자동 승인&lt;/span&gt;<br>  &lt;/label&gt;<br>  &lt;%# 수동 승인 라디오도 동일 — checked 여부만 organization.approvalMode로 갈림 %&gt;<br>&lt;/div&gt;</pre><p>라우트도 토글과 똑같은 모양입니다. 저장한 뒤 <strong>같은 블록을 다시 렌더해 반환</strong>합니다(토스트는 헤더로, 4–3).</p><pre>app.post(&#39;/api/update-approval-mode&#39;, async (req, res) =&gt; {<br>  const { token, approvalMode } = req.body;<br>  assert400(Object.values(ApprovalMode).includes(approvalMode), &#39;올바른 승인 모드 값이 아닙니다.&#39;);<br>  await organizationService.updateOrganization(organizationId, { approvalMode });   // 저장<br>  const organization = await organizationService.getOrganization(organizationId);<br>  hxToast(res, &#39;연차 승인 모드가 업데이트되었습니다.&#39;);<br>  res.render(&#39;partials/hx/settings-approval-mode&#39;, { organization, token, ApprovalMode });<br>});</pre><p>이 패턴으로 설정 화면의 여러 곳을 통일했습니다. 토글이든 라디오든, 각 컨트롤이 바뀌면 서버가 그 부분의 새 HTML을 렌더해 내려주고, htmx는 그 자리를 받은 HTML로 통째로 교체합니다.</p><p>여기서도 테스트로 못을 박아 둡니다. “선택한 라디오가 checked로 따라오는가&quot;를 정규식으로 검증하면, 라디오 SSOT(선택 상태를 서버가 그린다)가 깨지는 회귀를 바로 잡습니다.</p><pre>it(&#39;승인 모드(htmx) → 저장 + 선택 블록을 새 상태로 렌더 + 토스트&#39;, async () =&gt; {<br>  const { organization, token } = await makeAdmin();<br>  const res = await request(app)<br>    .post(&#39;/api/update-approval-mode&#39;).set(&#39;HX-Request&#39;, &#39;true&#39;).type(&#39;form&#39;)<br>    .send({ token, approvalMode: ApprovalMode.AUTO });<br><br>  expect(res.status).toBe(200);<br>  expect(res.text).toContain(&#39;id=&quot;approval-mode-options&quot;&#39;);  // JSON이 아니라 HTML 조각<br>  expect(res.text).toMatch(/value=&quot;auto&quot;[^&gt;]*\bchecked\b/s);  // 자동 승인이 checked로 렌더(SSOT)<br>  expect(res.headers[&#39;hx-trigger&#39;]).toContain(&#39;hxToast&#39;);     // &quot;저장되었습니다&quot; 토스트 헤더<br>  const updated = await organizationService.getOrganization(organization.organizationId);<br>  expect(updated?.approvalMode).toBe(ApprovalMode.AUTO);      // 실제 저장<br>});</pre><p>두 예시 모두 같은 모양의 테스트가 따라옵니다. HTTP 요청 한 번 + 응답 HTML(과 DB 상태) 검증이면 충분하니, 화면을 옮길 때마다 테스트가 거의 공짜로 붙고, 그만큼 다음 작업(특히 AI에게 맡기는 작업)의 안전망이 두꺼워집니다.</p><h3>4–3. 공통 처리 — 확인과 토스트</h3><p>화면마다 반복되는 공통 동작은 딱 두 가지였습니다. 작업 <strong>전</strong> “정말 하시겠습니까?” 확인과, 작업 <strong>후</strong> “저장되었습니다” 토스트. 둘 다 클라이언트에 코드를 흩어 두지 않고 한 번만 만들어 선언적으로 씁니다.</p><p><strong>작업 전 확인</strong> — 버튼에 hx-confirm만 달면, 네이티브 confirm() 대신 커스텀 모달이 뜨고 확인을 눌러야 요청이 나갑니다.</p><pre>&lt;button hx-delete=&quot;/teams/3?token=...&quot; hx-confirm=&quot;정말 삭제하시겠습니까?&quot; ...&gt;삭제&lt;/button&gt;</pre><p><strong>작업 후 토스트</strong> — 메시지는 서버가 정합니다. 그런데 이 문서가 줄곧 강조한 패턴(“변경 후 갱신된 <strong>HTML 조각</strong>을 반환”)에서는 응답 body가 HTML이라 “저장되었습니다” 같은 메시지를 실을 자리가 없습니다.</p><p>이때 쓰는 것이 htmx의 HX-Trigger <strong>응답 헤더</strong>입니다. htmx는 응답에 이 헤더가 있으면, 그 값을 읽어 <strong>같은 이름의 DOM 이벤트를 </strong><strong>document.body에서 dispatch</strong>합니다. 값이 JSON 객체면 key가 이벤트 이름, value가 그 이벤트의 event.detail이 됩니다.</p><p>즉 서버가 헤더 한 줄로 &quot;클라이언트에서 이 이벤트를 쏴라&quot;라고 지시하는, 일종의 서버 → 클라이언트 이벤트 푸시입니다(요청-응답 사이클 안에서).</p><pre>const hxToast = (res: Response, message: string, type: &#39;success&#39; | &#39;error&#39; = &#39;success&#39;): void =&gt; {<br>  res.setHeader(&#39;HX-Trigger&#39;, JSON.stringify({ hxToast: { m: encodeURIComponent(message), type } }));<br>};</pre><p>받는 쪽은 htmx-helpers.ejs에 등록된 단 하나의 <strong>글로벌 리스너</strong>입니다. body에서 발행된 이벤트가 버블링으로 document까지 올라오면 여기서 잡아 실제 토스트 UI를 띄웁니다.</p><pre>// 서버가 HTML 조각 + HX-Trigger 헤더를 함께 내려주면, htmx가 body에 &#39;hxToast&#39; 이벤트를 dispatch한다.<br>document.addEventListener(&#39;hxToast&#39;, (evt) =&gt; {<br>  if (typeof window.showToast !== &#39;function&#39;) return;<br>  const d = (evt &amp;&amp; evt.detail) || {};<br>  let msg = &#39;저장되었습니다&#39;;<br>  try { msg = d.m ? decodeURIComponent(d.m) : (d.message || msg); } catch (_) { msg = d.message || msg; }<br>  window.showToast(msg, d.type || &#39;success&#39;);<br>});</pre><p>전체 흐름은 이렇습니다.</p><pre>서버  res.setHeader(&#39;HX-Trigger&#39;, {hxToast:{m, type}})  +  HTML 조각<br>  │<br>  ▼  htmx가 응답 헤더를 파싱<br>htmx  document.body 에 &#39;hxToast&#39; 이벤트 dispatch (detail = {m, type})<br>  │<br>  ▼  버블링<br>공통  addEventListener(&#39;hxToast&#39;, ...)  →  window.showToast(msg, type)</pre><p>즉 서버는 <strong>한 번의 응답에 두 가지를 같이 실어 보냅니다</strong> — 응답 body에는 갈아끼울 HTML을, 응답 헤더(HX-Trigger)에는 띄울 토스트 정보를.</p><p>htmx는 body로 화면을 교체하면서 동시에 헤더를 읽어 토스트 이벤트를 쏩니다. 그래서 추가 요청도, &quot;저장됐으면 알림 띄우기&quot; 같은 클라이언트 분기 코드도 없이, <strong>한 응답으로 화면 교체와 알림이 같이</strong> 끝납니다.</p><blockquote><em>정리하면, htmx는 응답 한 번에 “무엇을 그릴지(body)”와 “무슨 이벤트를 쏠지(</em><em>HX-Trigger 헤더)&quot;를 함께 실어 보냅니다.</em></blockquote><h3>마치며</h3><p>백엔드 개발자인 저에게 htmx는 <strong>프론트의 일을 다시 서버 쪽으로 가져오는</strong> 도구였습니다. 화면을 그리는 책임이 서버 하나로 모이니, 화면마다 흩어져 있던 fetch·innerHTML·reload 핸들러가 사라지고 그 자리를 서버 템플릿과 hx-* 속성 몇 개가 대신하게 됐습니다.</p><p>여기서 얻은 두 가지가 컸습니다. 하나는 <strong>진실의 원천이 서버로 모인 것</strong>입니다. 클라이언트가 따로 상태를 들고 화면을 그리지 않으니, “숫자가 안 맞는” 류의 불일치 버그가 줄었습니다.</p><p>다른 하나는 <strong>테스트가 싸진 것</strong>입니다. 서버가 HTML을 반환하니 요청 한 번에 응답을 검증하면 되고, 앞으로 프론트를 AI에 맡기더라도 이 테스트들이 회귀를 잡아 줍니다 — 사람이 일일이 보지 않아도 안전망이 깔려 있는 셈입니다.</p><p>물론 htmx가 만능은 아닙니다. 실시간 편집·드래그·달력 같은 진짜 인터랙션은 여전히 클라이언트의 몫입니다.</p><p>핵심은 “전부 서버로”가 아니라 ”<strong>서버가 그릴 수 있는 것은 서버가 그리게 해서, 클라이언트가 짊어지던 짐을 덜어내는 것</strong>”입니다.<br>백엔드 개발자에게 이 전환은 꽤 남는 장사였습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f985c08896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a 3-Hour Query from the AI Team Broke My Index Only Scan]]></title>
            <link>https://medium.com/@letnaturebe2/how-a-3-hour-query-from-the-ai-team-broke-my-index-only-scan-a18b253b0139?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a18b253b0139</guid>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Tue, 26 May 2026 13:12:36 GMT</pubDate>
            <atom:updated>2026-05-26T13:12:36.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQGHSf8Z1bPxUB4kos04pQ.png" /></figure><p>I was tuning a hot read path in production. The query was simple, the index was right, and EXPLAIN showed a clean Index Only Scan. Sub-millisecond latency. I moved on.</p><p>A few weeks later, the same query was suddenly slow. Same query, same index, same data shape — but now EXPLAIN (ANALYZE, BUFFERS) showed Heap Fetches exploding. The Index Only Scan was technically still happening, but it was hitting the heap for almost every row, which defeated the entire point.</p><p>My first instincts were wrong. The index wasn’t bloated. Statistics were fresh. Nothing about the query plan had changed. The culprit turned out to be something I never would have guessed by looking at the slow query itself: <strong>a long-running transaction in a completely unrelated part of the system was preventing VACUUM from doing its job.</strong></p><p>This post is about why that happens, and why PostgreSQL is especially unforgiving about it.</p><h3>Dead tuples and the Visibility Map</h3><p>In PostgreSQL, UPDATE and DELETE don&#39;t actually overwrite or remove rows. They mark the old version as <strong>dead</strong> and (for UPDATE) write a new version next to it. The dead versions stay in the heap until VACUUM cleans them up.</p><p>When VACUUM confirms a heap page has no live dead tuples and nothing in-flight, it flips a bit in the <strong>Visibility Map (VM)</strong> — one bit per page saying “everything here is visible to everyone.” Index Only Scan trusts that bit to skip the heap.</p><p>No clean pages → no VM bits set → no Index Only Scan. You’re back to heap fetches.</p><h3>What a long transaction actually does</h3><p>VACUUM was still running on my table. autovacuum logs confirmed it. But nothing was getting cleaned up.</p><p>The reason: VACUUM can only remove a dead tuple if no living transaction could possibly still need to see the old version. It computes the <strong>globally oldest xmin</strong> across every active backend in the cluster, and refuses to remove anything that became dead after that snapshot.</p><p>In rough pseudocode:</p><pre># Recomputed at the start of each VACUUM cycle.<br># A single min() across every active backend in the entire cluster.<br>oldest_xmin = min(backend.xmin for backend in all_active_backends)<br><br>for tuple in dead_tuples_on_page:<br>    if tuple.xmax &lt; oldest_xmin:<br>        remove(tuple)    # died before the oldest snapshot — safe<br>    else:<br>        keep(tuple)      # &quot;dead but not yet removable&quot;</pre><p>The whole story is in that min(). As long as one backend is sitting on a small xmin, the horizon can&#39;t advance — and every dead tuple produced after that snapshot falls into the else branch.</p><p>The AI team’s query held a snapshot for 5 hours. For 5 hours, its backend’s xmin was the smallest in the cluster, and min() kept returning that same tiny value. Every UPDATE and DELETE on every table during that window produced dead tuples with xmax &gt; oldest_xmin — so VACUUM left every single one of them behind. VACUUM VERBOSE was literally reporting them as dead but not yet removable.</p><p>No tuples removed → pages never qualify as all-visible → VM bits never set → my Index Only Scan kept hitting the heap.</p><h3>The counterintuitive part</h3><p>I would have guessed a long transaction only affects tables it actually touches. It doesn’t. PostgreSQL’s vacuum horizon is <strong>cluster-wide</strong>, not table-wide and not even database-wide. A long-running SELECT on analytics.huge_table holds back VACUUM on app.users in a different database on the same instance.</p><p>So an AI team query on their analytics tables silently degraded my production reads on completely unrelated tables.</p><h3>Takeaway</h3><p>A single careless long transaction — even a read-only one on completely unrelated tables — can quietly break Index Only Scan across the entire cluster. The chain is: long transaction → VACUUM can’t remove dead tuples → Visibility Map stops updating → Index Only Scan degrades into heap fetches.</p><p>backend_xmin is the most underrated column in pg_stat_activity. When a query mysteriously slows down and the plan still looks right, look there first.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18b253b0139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Exception Handling with asserts]]></title>
            <link>https://medium.com/@letnaturebe2/typescript-exception-handling-with-asserts-1c9ab573c086?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c9ab573c086</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 10:31:54 GMT</pubDate>
            <atom:updated>2026-03-28T10:31:54.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiigtMSx9B7en_PnvlWfcw.png" /></figure><p>In web development, assert is rarely used. Most developers associate it with C/C++ or test code. But I&#39;ve been actively using a simple assert helper function throughout my production code. It gives me readability, early exit, and TypeScript&#39;s type safety all at once.</p><p>When developing with TypeScript, you end up repeating code like this over and over:</p><pre>const user: User | null = await userService.getUser(userId);<br>if (!user) {<br>  throw new Error(&#39;User not found&#39;);<br>}<br>// now user is not null<br>user.name;</pre><p>Once or twice is fine, but when a single function has 5 or 6 of these checks in a row, half the code becomes if/throw boilerplate.</p><p>What’s even more frustrating is that if you extract this validation logic into a function, <strong>TypeScript loses type narrowing</strong>.</p><pre>function validate(value: unknown, message: string) {<br>  if (!value) throw new Error(message);<br>}<br><br>const user: User | null = await userService.getUser(userId);<br>validate(user, &#39;User not found&#39;);<br>user.name; // ❌ Compile error: &#39;user&#39; is possibly &#39;null&#39;</pre><p>From the TypeScript compiler’s perspective, it has no idea what validate() does. It&#39;s just a void function. Your IDE shows a red squiggly line under user.name, and the build fails.</p><h3>asserts — Telling the compiler &quot;if this function returns, the condition is true&quot;</h3><p>The <strong>assertion function</strong> introduced in TypeScript 3.7 solves exactly this problem.</p><pre>function assert(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new Error(message);<br>}</pre><p>By writing asserts condition in the return type position, you&#39;re declaring to the TypeScript compiler:</p><blockquote><em>“If this function returns without throwing, the </em><em>condition argument is </em><em>true.&quot;</em></blockquote><p>At runtime, it behaves exactly like void. It returns nothing. But at compile time, <strong>type narrowing</strong> kicks in.</p><pre>const user: User | null = await userService.getUser(userId);<br><br>assert(user !== null, &#39;User not found&#39;);<br>// from this line on, user: User ✅</pre><p>One line handles both <strong>runtime validation (throw)</strong> and <strong>compile-time type guarantee (narrowing)</strong> simultaneously.</p><h3>Real-world production usage</h3><p>I’ve been using this pattern extensively while developing a <a href="https://newvibot.com/">Slack PTO management app</a>.</p><h3>Enforcing business rules at the service layer</h3><p>Here’s the entry point of the createPtoRequest function that creates a PTO request.</p><pre>@Transactional()<br>async createPtoRequest(<br>  user: User,<br>  template: PtoTemplate,<br>  startDate: Date,<br>  endDate: Date,<br>  title: string,<br>  reason: string,<br>  approvers: User[],<br>): Promise&lt;PtoRequest&gt; {<br>  assert(approvers.length &gt; 0, &#39;At least one approver is required for PTO requests&#39;);<br>  assert(startDate &lt;= endDate, &#39;Start date must be before end date&#39;);<br><br>  if (template.daysConsumed &lt; 1 &amp;&amp; template.daysConsumed &gt; 0) {<br>    assert(<br>      isSameDay(startDate, endDate),<br>      &#39;Start and end date must be the same for templates that consume less than 1 day&#39;,<br>    );<br>  }<br><br>  // business logic follows...<br>}</pre><p>Three invariants are declared at the function’s entry point:</p><ol><li>There must be <strong>at least one approver</strong>.</li><li>The <strong>start date must be before the end date</strong>.</li><li>For templates that consume <strong>less than one day</strong> (like half-day leave), start and end dates must be the same.</li></ol><p>Without these three lines? You’d either have 3 more if/throw blocks, risk invalid data reaching the database, or force every caller to validate. By placing asserts at the service function entry point, <strong>the function’s contract is immediately visible in the first few lines of code</strong>.</p><h3>Extending to web backends: HTTP status code asserts</h3><p>The basic assert throws a plain Error. But in web backends, you need to throw errors with specific <strong>HTTP status codes</strong> like 400, 401, 403, 404. So I created an error class and assert variants for each.</p><pre>export class HttpError extends Error {<br>  constructor(public statusCode: number, message: string) {<br>    super(message);<br>    this.name = &#39;HttpError&#39;;<br>  }<br>}<br><br>export function assert(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new Error(message);<br>}<br>export function assert400(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(400, message);<br>}<br>export function assert401(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(401, message);<br>}<br>export function assert403(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(403, message);<br>}<br>export function assert404(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(404, message);<br>}</pre><p>These five functions are all there is. Each is a one-liner, but look at how effective this simplicity is in practice.</p><p>Frameworks like NestJS often handle input validation before the controller via DTO validation (class-validator, etc.). But there are validations that DTO validation simply cannot cover. “Is this user an admin?” requires a database lookup. “Does this resource exist?” is the same. These <strong>403, 400, 404 errors that arise within business logic</strong> can’t be caught at the DTO layer. This is exactly where assert shines.</p><pre>// billing page route — billing.ts<br>app.get(&#39;/billing-html&#39;, async (req, res) =&gt; {<br>  const decoded = verifyJwt(token as string);     // throws 401 on failure<br>  const currentUser = await userService.getUser(decoded.userId);<br>  const organization = await organizationService.getOrganization(decoded.organizationId);<br><br>  assert403(currentUser.isAdmin, &#39;Admin privileges required.&#39;);<br>  assert400(organization !== null, &#39;Organization not found&#39;);<br><br>  // from here, currentUser is admin and organization exists — guaranteed<br>  // focus on business logic only<br>  res.render(&#39;pages/billing&#39;, { currentUser, organization, ... });<br>});</pre><p>Without assert, this handler would have at least 3 if/throw or if/return + res.status().json() blocks. Thanks to the assert pattern, <strong>validation is one line, the rest is business logic</strong>.</p><h3>Combining with a global error handler</h3><p>Who handles the HttpError thrown by assert? A single global error handler is all you need.</p><pre>const errorHandler: ErrorRequestHandler = (err, req, res, next) =&gt; {<br>  const isHttpError = err instanceof HttpError;<br>  const statusCode = isHttpError ? err.statusCode : 500;<br><br>  // 4xx: client error, but worth tracking<br>  if (isHttpError &amp;&amp; statusCode &gt;= 400 &amp;&amp; statusCode &lt; 500) {<br>    logWarn(`[${statusCode}] ${err.message}`, { path: req.path });<br>  }<br><br>  // 5xx: server error — needs immediate attention<br>  if (!isHttpError || statusCode &gt;= 500) {<br>    logError(&#39;Unexpected server error&#39;, err);<br>  }<br><br>  res.status(statusCode).json({<br>    message: isHttpError ? err.message : &#39;Internal Server Error&#39;,<br>  });<br>};</pre><p>The number in assert <strong>determines the response code, logging level, and even notification policy all at once</strong>. assert400 results in a 400 response + warn log. A plain assert results in a 500 response + error log — and you can connect Sentry reports or Slack notifications on top. Each handler doesn&#39;t need to care about error response formatting or alerting at all. Just use an assert, and the global error handler takes care of the rest.</p><h3>Wrapping up</h3><p>A single assert line gives you validation and early exit simultaneously. After it, you can focus on business logic with guaranteed types — no unnecessary null checks. Create variants like assert400 and assert403, and HTTP status codes are captured in one line too. Error responses are handled centrally by the global error handler.</p><p>This isn’t a complex library or a new paradigm. It’s using TypeScript’s type system to make the if/throw you were already writing <strong>shorter and type-safe</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c9ab573c086" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript로 Exception Handling하기]]></title>
            <link>https://medium.com/@letnaturebe2/typescript%EB%A1%9C-exception-handling%ED%95%98%EA%B8%B0-f6cd9139a3ff?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6cd9139a3ff</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 10:17:53 GMT</pubDate>
            <atom:updated>2026-03-28T10:21:27.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>assert로 TypeScript Exception Handling하기</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiigtMSx9B7en_PnvlWfcw.png" /></figure><p>웹 개발에서는 assert를 잘 쓰지 않는다.<br>C/C++ 또는 테스트 코드에서나 쓰는 것이라는 인식이 강하다.</p><p>하지만 나는 간단한 assert 헬퍼 함수를 만들어서 프로덕션 코드 전반에 걸쳐 적극적으로 사용하고 있다.</p><p>가독성과 early exit, 그리고 TypeScript의 타입 안전성까지 한 번에 챙길 수 있기 때문이다.</p><p>TypeScript로 개발하다 보면 이런 코드를 수없이 반복하게 된다.</p><pre>const user: User | null = await userService.getUser(userId);<br>if (!user) {<br>  throw new Error(&#39;User not found&#39;);<br>}<br>// 이제 user는 null이 아님<br>user.name;</pre><p>한두 번은 괜찮지만, 하나의 함수에서 이런 검증이 5~6개 연달아 나오면 코드의 절반이 if/throw 보일러플레이트로 채워진다.</p><p>더 짜증나는 건, 이 검증 로직을 함수로 추출하면 <strong>TypeScript가 타입 좁히기를 못 한다</strong>는 점이다.</p><pre>function validate(value: unknown, message: string) {<br>  if (!value) throw new Error(message);<br>}<br><br>const user: User | null = await userService.getUser(userId);<br>validate(user, &#39;User not found&#39;);<br>user.name; // ❌ 컴파일 에러: &#39;user&#39; is possibly &#39;null&#39;</pre><p>TypeScript 컴파일러 입장에서는 validate()가 뭘 하는지 모른다. <br>그냥 void 반환 함수일 뿐이다. IDE에서 user.name에 빨간 줄이 뜨고, 빌드도 실패한다.</p><h4>asserts — 컴파일러에게 &quot;이 함수를 통과하면 이 조건은 참이다&quot;라고 알려주기</h4><p>TypeScript 3.7에서 도입된 <strong>assertion function</strong>이 정확히 이 문제를 해결한다.</p><pre>function assert(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new Error(message);<br>}</pre><p>반환 타입 자리에 asserts condition을 쓰면, TypeScript 컴파일러에게 이렇게 선언하는 것이다</p><blockquote><em>“이 함수가 throw 없이 정상 리턴했다면, </em><em>condition 인자는 </em><em>true다.&quot;</em></blockquote><p>런타임에는 void와 똑같이 동작한다. 아무것도 반환하지 않는다. 하지만 컴파일 타임에는 <strong>타입 좁히기(narrowing)</strong>가 작동한다.</p><pre>const user: User | null = await userService.getUser(userId);<br><br>assert(user !== null, &#39;User not found&#39;);<br>// 이 줄을 지나면 user: User ✅</pre><p>한 줄로 <strong>런타임 검증(throw)</strong>과 <strong>컴파일 타임 타입 보장(narrowing)</strong>을 동시에 처리한다.</p><h4>실제 프로덕션 코드에서의 활용</h4><p>나는 Slack 휴가 관리 앱(<a href="https://newvibot.com/">https://newvibot.com</a>)을 개발하면서 이 패턴을 전역적으로 사용하고 있다.</p><p>휴가 신청을 생성하는 createPtoRequest 함수의 진입점이다.</p><pre>@Transactional()<br>async createPtoRequest(<br>  user: User,<br>  template: PtoTemplate,<br>  startDate: Date,<br>  endDate: Date,<br>  title: string,<br>  reason: string,<br>  approvers: User[],<br>): Promise&lt;PtoRequest&gt; {<br>  assert(approvers.length &gt; 0, &#39;At least one approver is required for PTO requests&#39;);<br>  assert(startDate &lt;= endDate, &#39;Start date must be before end date&#39;);<br><br>  if (template.daysConsumed &lt; 1 &amp;&amp; template.daysConsumed &gt; 0) {<br>    assert(<br>      isSameDay(startDate, endDate),<br>      &#39;Start and end date must be the same for templates that consume less than 1 day&#39;,<br>    );<br>  }<br>  // 이후 비즈니스 로직...<br>}</pre><p>함수 진입점에서 세 가지 조건(invariant)을 선언하고 있다:</p><ol><li><strong>승인자가 최소 1명</strong> 있어야 한다.</li><li><strong>시작일이 종료일보다 앞서야</strong> 한다.</li><li>반차처럼 <strong>소진일이 1일 미만인 템플릿</strong>은 시작일과 종료일이 같아야 한다.</li></ol><p>이 세 줄이 없다면? if/throw 블록이 3개 늘어나거나, 검증 없이 잘못된 데이터가 DB에 들어가거나, 또는 호출하는 쪽에서 매번 검증해야 한다. <br>assert를 서비스 함수 진입점에 두면, <strong>이 함수의 계약(contract)이 코드 첫 몇 줄에 바로 드러난다.</strong></p><h4>웹 백엔드로의 확장: HTTP 상태 코드별 assert</h4><p>기본 assert는 일반 Error를 던진다. 하지만 웹 백엔드에서는 400, 401, 403, 404 등 <strong>HTTP 상태 코드에 맞는 에러</strong>를 던져야 한다. 그래서 이런 에러 클래스와 assert variant를 만들었다.</p><pre>export class HttpError extends Error {<br>  constructor(public statusCode: number, message: string) {<br>    super(message);<br>    this.name = &#39;HttpError&#39;;<br>  }<br>}<br><br>export function assert(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new Error(message);<br>}<br>export function assert400(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(400, message);<br>}<br>export function assert401(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(401, message);<br>}<br>export function assert403(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(403, message);<br>}<br>export function assert404(condition: boolean, message: string): asserts condition {<br>  if (!condition) throw new HttpError(404, message);<br>}</pre><p>이 다섯 개의 함수가 전부다. 각각 한 줄짜리지만, 실제 사용 예시를 보면 이 단순함이 얼마나 효과적인지 알 수 있다.</p><p>물론 NestJS 같은 프레임워크에서는 DTO validation(class-validator 등)으로 입력 검증을 컨트롤러 진입 전에 처리하는 경우가 많다.</p><p>하지만 DTO validation만으로는 해결할 수 없는 검증이 있다. <br>“이 사용자가 관리자인가?”는 DB를 조회해야 알 수 있고,<br> “이 리소스가 존재하는가?”도 마찬가지다.</p><p>이런 <strong>비즈니스 로직 안에서 발생하는 403, 400, 404</strong>는 DTO 레이어에서 잡을 수 없다. assert가 빛나는 지점이 바로 여기다.</p><pre>// 결제 페이지 라우트 — billing.ts<br>app.get(&#39;/billing-html&#39;, async (req, res) =&gt; {<br>  const decoded = verifyJwt(token as string);     // 실패 시 401<br>  const currentUser = await userService.getUser(decoded.userId);<br>  const organization = await organizationService.getOrganization(decoded.organizationId);<br>  <br>  assert403(currentUser.isAdmin, &#39;관리자 권한이 필요합니다.&#39;);<br>  assert400(organization !== null, &#39;Organization not found&#39;);<br>  // 여기부터는 currentUser가 admin이고, organization이 존재함이 보장됨<br>  <br>  // 비즈니스 로직에만 집중<br>  res.render(&#39;pages/billing&#39;, { currentUser, organization, ... });<br>});</pre><p>assert가 없다면 이 핸들러에는 if/throw 또는 if/return + res.status().json() 블록이 최소 3개는 들어갔을 것이다.</p><p>assert 패턴 덕분에 <strong>검증은 한 줄, 나머지는 비즈니스 로직</strong>이라는 구조가 유지된다.</p><h4>글로벌 에러 핸들러와의 조합</h4><p>위 코드에서 assert가 던진 HttpError는 누가 처리할까? <strong>글로벌 에러 핸들러 </strong>하나면 된다.</p><pre>const errorHandler: ErrorRequestHandler = (err, req, res, next) =&gt; {<br>  const isHttpError = err instanceof HttpError;<br>  const statusCode = isHttpError ? err.statusCode : 500;<br><br>  // 400번대: 클라이언트 잘못이지만 추적할 가치가 있음<br>  if (isHttpError &amp;&amp; statusCode &gt;= 400 &amp;&amp; statusCode &lt; 500) {<br>    logWarn(`[${statusCode}] ${err.message}`, { path: req.path });<br>  }<br>  // 500번대: 서버 에러 - 즉시 확인 필요<br>  if (!isHttpError || statusCode &gt;= 500) {<br>    logError(&#39;Unexpected server error&#39;, err);<br>  }<br>  res.status(statusCode).json({<br>    message: isHttpError ? err.message : &#39;Internal Server Error&#39;,<br>  });<br>};</pre><p>assert의 숫자가 <strong>에러 응답 코드와 로깅 레벨을 동시에 결정</strong>한다. <br>assert400은 400 응답 + warn 로그, <br>일반 assert는 500 응답 + error 로그. 각 핸들러에서는 에러 응답 형식을 전혀 신경 쓰지 않아도 된다.<br>(필요하다면 sentry report, slack 알림을 넣어도 된다.)</p><h3>정리</h3><p>assert 한 줄이면 검증과 동시에 early exit이 이루어지고, 이후 코드에서는 불필요한 null 체크 없이 타입이 보장된 상태로 비즈니스 로직에 집중할 수 있다.</p><p>assert400, assert403 같은 variant를 만들면 HTTP 상태 코드까지 한 줄에 담기고, 에러 응답은 글로벌 에러 핸들러에서 일괄 처리하면 된다.</p><p>결국 복잡한 라이브러리나 새로운 패러다임이 아니다. TypeScript가 제공하는 타입 시스템 기능을 활용해서, 이미 작성하고 있던 if/throw를 <strong>더 짧고, 타입 안전하게</strong> 바꾸는 것이다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6cd9139a3ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Real-World DB Lock Story (Infinite Login Loading)]]></title>
            <link>https://medium.com/@letnaturebe2/a-real-world-db-lock-story-infinite-login-loading-12f10b21b389?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f10b21b389</guid>
            <category><![CDATA[db-lock]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[update-lock]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 00:44:25 GMT</pubDate>
            <atom:updated>2026-03-01T00:44:25.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXKUZAeVO_raLRWxNIJltQ.png" /></figure><p>Most of us know that running an `UPDATE` query in a Relational Database (RDB) locks the affected row. Whenever we try to explain this concept, we usually fall back on the classic textbook example: *”User A transfers $10 to User B.”*</p><p>But recently at work, I experienced a much more realistic (and memorable) scenario. It wasn’t a catastrophic service outage — just a minor, somewhat comical incident where *only my account* couldn’t log in. It turned out to be the perfect real-world example to explain how DB locks actually work in practice, so I decided to write it down.</p><h4>A Quick Recap on RDB Update Locks</h4><p>Before we dive in, let’s quickly review what happens when you run an `UPDATE`. <br>Typically, an <strong>Exclusive Lock</strong> is placed on the affected record.</p><p>While this lock is active, the following rules apply:</p><ul><li><strong>Allowed (Pass)</strong>: Normal `SELECT` queries (simple reads).</li><li><strong>Blocked (Wait)</strong>: Other transactions trying to `UPDATE`, `DELETE`, or `SELECT FOR UPDATE`.</li></ul><p>Whether your Isolation Level is `READ COMMITTED` or `REPEATABLE READ`, this general rule remains the same (simple `SELECT`s will just read the previous version of the data without waiting).</p><h4>How It Started: “I changed your nickname, try logging in.”</h4><p>A while ago, a fellow developer needed to arbitrarily modify my account data (in the `User` table) for testing purposes. <br>(Not the best practice in production, but it happens during development!)</p><p>My colleague opened their DB tool (like DataGrip or pgAdmin), turned off the Auto-commit feature to prevent any mistakes, and ran the following query in manual mode:</p><pre>BEGIN; <br>UPDATE user SET nickname = &#39;letnaturebe&#39; WHERE user_id = &#39;my_account&#39;;</pre><p>Without committing the transaction yet, they turned to me and said:</p><p>“I just changed your nickname. Try logging in to check if it works.”</p><h4>Wait, Why Is Only My Account Unresponsive?</h4><p>I tried logging in with my ID. But… there was absolutely no response from the server. Just an infinite loading spinner.</p><p>Thinking, ’Did the server go down?’,<br>I asked my colleague if they could log in with their own account.</p><p>”Mine works perfectly fine,” they replied.</p><p>I pondered for a minute or two. What on earth is going on? Everyone else can log in, but only my account is hanging? Suddenly, it hit me.</p><p>‘Ah! My login request is currently blocked, waiting to acquire the Update Lock that my colleague is holding on my account!’</p><h4>The Mystery: Isn’t Login Just a Simple SELECT?</h4><p>But another question immediately popped into my head.</p><p>”Wait, logging in is just a simple `SELECT` to read user info. It shouldn’t care about the lock and should read the data immediately, right?”*</p><p>So, I opened the login API code. And there, I found the culprit.</p><pre>// Inside the login logic<br>// 1. SELECT * FROM user WHERE user_id = &#39;my_account&#39;; // This works perfectly!<br>// 2. Password validation logic...<br>// 3. UPDATE user SET last_login = now() WHERE user_id = &#39;my_account&#39;; // 👈 BLOCKING HAPPENS HERE!</pre><p>The login logic wasn’t <strong>just</strong> reading data.<br>It was also updating the `last_login` field to record the exact moment the user logged in!</p><p>Because my colleague’s `UPDATE` transaction hadn’t been committed yet, the `UPDATE` statement inside the login API couldn’t acquire the Exclusive Lock and was left hanging indefinitely.</p><h4>The Resolution</h4><p>Fully understanding the situation, I turned to my colleague and laughed.</p><p>“Please, just press commit once!”</p><p>As soon as they executed the `COMMIT`, my waiting query instantly acquired the lock, ran successfully, and my login was completed.</p><h4>Wrapping Up</h4><p>Whenever I had to explain database concurrency issues or locks, I always resorted to the boring bank transfer example. But experiencing this firsthand — where an uncommitted manual query collides with a hidden `UPDATE` inside a seemingly simple Login API — was such a fun and practical lesson.</p><p>Next time you need to explain DB locks to someone, maybe skip the bank transfer and tell them this “Infinite Login Loading” story instead!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f10b21b389" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Junior Developer Read from Master and Still Got Old Data]]></title>
            <link>https://medium.com/@letnaturebe2/a-junior-developer-read-from-master-and-still-got-old-data-936458db5e47?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/936458db5e47</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[dbs]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 08:32:14 GMT</pubDate>
            <atom:updated>2025-12-14T08:32:14.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3GF2x__Nwk-yMLtQUsOrQ.png" /></figure><h3>Introduction</h3><p>A <strong>database transaction</strong> groups multiple operations —</p><p>INSERT, UPDATE, DELETE — into a single unit of work.<br>By calling commit or rollback, the database guarantees that <strong>all changes either succeed together or fail together</strong>.</p><p>Two rules are especially important:</p><ul><li>Until commit is called, changes are <strong>not permanently persisted</strong></li><li>Uncommitted changes are <strong>only visible inside the same transaction</strong></li><li>They are <strong>never visible to other database connections</strong></li></ul><p>Because of this, even within the same HTTP request,<br>reading data using a different connection can return <strong>old values</strong>.<br>This article is about a real-world bug caused by exactly that.</p><h3>The System Setup</h3><p>Our system uses a <strong>Master / Replica</strong> database architecture:</p><ul><li><strong>Master DB<br></strong>Handles INSERT, UPDATE, DELETE</li><li><strong>Read Replica<br></strong>Handles SELECT, asynchronously replicated from master</li></ul><p>We use <strong>AWS RDS Read Replicas</strong>.<br>Replication usually completes within 1–2 seconds, but it is <strong>not real-time</strong>.</p><p>So the team already followed a well-known rule:</p><blockquote>If you need to read immediately after a write, read from the <strong>master</strong>.</blockquote><p>And yes — the code did read from the master.<br>Yet the bug still happened.</p><h3>The Buggy Assumption</h3><p>The junior developer’s assumption was reasonable:</p><ul><li>“I updated the data on the <strong>master DB</strong>”</li><li>“I also read from the <strong>master DB</strong>”</li><li>“So I should get the latest data”</li></ul><p>But this assumption hides a critical detail:</p><blockquote><strong><em>Reading from master does not mean reading from the same transaction.</em></strong></blockquote><h3>The Actual Bug</h3><h3>❌ Reading from Master Using a New Connection</h3><pre>// user.service.ts<br><br>// This reads from the master DB,<br>// but it creates a brand-new connection (new transaction)<br>async function getUserFromMaster(id: number): Promise&lt;User | null&gt; {<br>  const newConnection = await writeDataSource<br>    .createQueryRunner()<br>    .connect()<br><br>  const userRepository = newConnection.manager.getRepository(User)<br>  return userRepository.findOne({ where: { id } })<br>}<br><br>export async function updateUser(dto: UpdateUserDto) {<br>  const queryRunner = writeDataSource.createQueryRunner()<br><br>  await queryRunner.connect()<br>  await queryRunner.startTransaction()<br><br>  // 1) UPDATE on master DB (not committed yet)<br>  await queryRunner.manager.update(User, dto.id, {<br>    name: dto.name,<br>    updatedAt: new Date()<br>  })<br><br>  // 2) Complex business logic<br>  await doSomething()<br><br>  // 3) ❌ SELECT runs in a different transaction<br>  const user = await getUserFromMaster(dto.id)<br><br>  // 4) ❌ Old data gets cached<br>  await redis.set(`user:${dto.id}`, JSON.stringify(user))<br><br>  await queryRunner.commitTransaction()<br><br>  return user<br>}</pre><h3>Why This Happened</h3><p>Even though both queries used the <strong>master DB</strong>, they ran in <strong>different transactions</strong>:</p><ul><li>UPDATE → Transaction A</li><li>SELECT → Transaction B (new connection)</li></ul><p>Transaction B can only see <strong>committed data</strong>.<br>Since the update had not been committed yet,</p><p>the SELECT returned <strong>the previous version of the user</strong>.<br>That stale data was then cached in Redis.</p><h3>The Root Cause</h3><p>This bug had nothing to do with:</p><p>❌ Replication delay</p><p>❌ Master vs replica routing</p><p>The real cause was:</p><blockquote><strong><em>Different connections = different transactions</em></strong></blockquote><p>Even inside the same web request.</p><h3>The Fix</h3><p>The solution is straightforward:</p><blockquote><strong><em>If you need to read data immediately after updating it,</em></strong></blockquote><blockquote><strong><em>you must read using the same transaction.</em></strong></blockquote><h3>Allow the read function to accept a transaction manager</h3><pre>async function getUserFromMaster(<br>  id: number,<br>  manager?: EntityManager<br>) {<br>  const repo = manager<br>    ? manager.getRepository(User) // same transaction<br>    : writeDataSource.getRepository(User)<br><br>  return repo.findOne({ where: { id } })<br>}</pre><h3>✅ Read using the same transaction after UPDATE</h3><pre>const user = await getUserFromMaster(dto.id, queryRunner.manager)<br>await redis.set(`user:${dto.id}`, JSON.stringify(user))</pre><p>Now:</p><ul><li>UPDATE and SELECT share the same transaction</li><li>Uncommitted changes are visible</li><li>Redis stores the correct, up-to-date data</li></ul><h3>Key Takeaway</h3><p>The most important lesson is this:</p><blockquote><strong><em>The problem wasn’t “master vs replica” —</em></strong></blockquote><blockquote><strong><em>it was “same transaction vs different transaction.”</em></strong></blockquote><h3>What We Learned</h3><ul><li>Uncommitted changes are visible <strong>only inside the same transaction</strong></li><li>“Outside the transaction” means <strong>any other connection</strong></li><li>This applies even within a single HTTP request</li><li>When reading data right after a write,</li><li><strong>always use the same EntityManager / transaction</strong></li></ul><h3>Final Thought</h3><p>This wasn’t a junior developer problem.</p><p>It was a <strong>transaction boundary problem</strong> — one that easily slips into production code.</p><p>If this article helped you avoid even one similar bug,<br>it already did its job.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936458db5e47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Transactions in TypeORM]]></title>
            <link>https://medium.com/@letnaturebe2/clean-transactions-in-typeorm-c99b87e09818?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99b87e09818</guid>
            <category><![CDATA[transactional]]></category>
            <category><![CDATA[typeorm]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 02:50:41 GMT</pubDate>
            <atom:updated>2025-09-16T12:03:43.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjXzO_eDEaAgNOQru3vFHQ.png" /></figure><h3>Stop passing the EntityManager around.</h3><p>If you’ve ever used TypeORM for a serious project, you’ve likely felt this pain. You have a complex operation — say, a user signup that needs to create a user, an organization, and link them together. This has to be a single, atomic transaction. If any step fails, everything must roll back.</p><p>So you reach for dataSource.transaction(), and suddenly your clean service layer is infected. You’re passing the EntityManager object from one method to the next, polluting function signatures and tightly coupling your business logic to the transaction’s state.</p><p>The code starts to feel awkward and messy. I kept looking at frameworks like Spring with its beautiful @Transactional annotation or Django’s atomic() block and feeling a sense of envy. Why couldn’t TypeORM be that simple?</p><p>I looked around for existing open-source solutions, but many seemed unmaintained or relied on outdated dependencies.</p><p><strong>So, I decided to build it myself.</strong> I’m introducing typeorm-transactional-service, a clean, zero-configuration library for handling transactions declaratively.</p><p>If you’ve felt this same frustration, this library is for you.</p><h3>The Pain: What We Used to Do</h3><p>Without a declarative approach, managing a transaction across multiple services is clumsy. You have a root method that starts the transaction, and then you have to pass the transactional EntityManager down to every single method that needs to participate.</p><p>It looks something like this:</p><pre>// The messy &quot;Before&quot;<br>export class SignupService {<br>  async signup(signupData: SignupDto) {<br>    return this.dataSource.transaction(async (manager) =&gt; {<br>      // 1. Create organization, passing the manager<br>      const organization = await this.organizationService.create(manager, {<br>        organizationId: signupData.organizationId,<br>      });<br><br>      // 2. Create user, passing the manager again<br>      const user = await this.userService.create(manager, {<br>        userId: signupData.userId,<br>      });<br>      <br>      // 3. Link them... using the manager<br>      user.organization = organization;<br>      await manager.save(user);<br><br>      return { organization, user };<br>    });<br>  }<br>}</pre><p>This pattern forces organizationService and userService to have methods that explicitly accept an EntityManager. It’s boilerplate, and it makes your services harder to test and reason about.</p><h3>The Solution: A Cleaner Way</h3><p>The solution is simple. Any service that needs to manage or participate in a transaction <strong>extends </strong><strong>BaseTransactionalService</strong>. This gives it access to a context-aware getRepository().</p><p>Then, you simply add the <strong>@Transactional()</strong> decorator to the method that should be the boundary of a transaction.</p><p>Let’s see how this approach completely transforms our complex signup workflow.</p><pre>// The clean &quot;After&quot;<br>import { BaseTransactionalService, Transactional } from &#39;typeorm-transactional-service&#39;;<br><br>export class SignupService extends BaseTransactionalService {<br>  constructor(<br>    dataSource: DataSource,<br>    private readonly organizationService: OrganizationService, // Also extends BaseTransactionalService<br>    private readonly userService: UserService // Also extends BaseTransactionalService<br>  ) {<br>    super(dataSource);<br>  }<br><br>  // All operations below run in a single, shared transaction<br>  @Transactional()<br>  async signup(signupData: SignupDto) {<br>    // 1. Call the first service. No manager passed.<br>    const organization = await this.organizationService.createOrganization({<br>      organizationId: signupData.organizationId,<br>    });<br><br>    // 2. Call the second service. Still no manager.<br>    const user = await this.userService.createUser({<br>      userId: signupData.userId,<br>    });<br><br>    // 3. Link them using our service&#39;s own getRepository()<br>    const userRepo = this.getRepository(User);<br>    user.organization = organization;<br>    await userRepo.save(user);<br><br>    return { organization, user };<br>  }<br>}</pre><p>It’s clean. It’s intuitive. The SignupService doesn’t need to know how the underlying services work, and the nested services—organizationService and userService—don’t need to be aware they are part of a larger transaction. The context is shared automatically.</p><p>If userService.createUser throws an error, the new organization created by organizationService is <strong>automatically rolled back</strong>. No data is left orphaned. This is how transaction management should be.</p><h3>How It Works (Under the Hood)</h3><p>This library uses <strong>Node.js </strong><strong>AsyncLocalStorage</strong> to maintain the transaction context across asynchronous operations.</p><ol><li>When a method decorated with @Transactional() is called, it gets or creates a transactional EntityManager and stores it in an AsyncLocalStorage context.</li><li>When you call this.getRepository() or this.getManager() from within your service, they are smart enough to first check for a manager in that context.</li><li>If one exists, they use it. If not, they fall back to the default DataSource manager.</li></ol><p>This allows the transaction to seamlessly propagate across service calls without you having to pass anything around. It just works.</p><h3>Give It a Try</h3><p>For too long, clean transaction management has been a missing piece in the TypeORM ecosystem. This library aims to fix that. It offers zero-configuration, automatic rollbacks, and seamless transaction propagation.</p><p>If you’re a TypeORM user who has been looking for a more elegant way to handle your data layer, I encourage you to check it out.</p><p>You can install it via npm:</p><pre>npm install typeorm-transactional-service</pre><p>The full source code and documentation are available on GitHub. Your feedback, issues, and contributions are welcome. Give it a <strong>star</strong> if you find it useful!</p><p><a href="https://github.com/letnaturebe2/typeorm-transactional">https://github.com/letnaturebe2/typeorm-transactional</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99b87e09818" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Node.js Single-Threaded or Multi-Threaded? Let’s End the Debate.]]></title>
            <link>https://medium.com/@letnaturebe2/is-node-js-single-threaded-or-multi-threaded-lets-end-the-debate-738d9d937015?source=rss-d7d3fbf712cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/738d9d937015</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[letnaturebe]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 23:35:03 GMT</pubDate>
            <atom:updated>2025-09-12T23:35:03.854Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ll often see articles claiming, “Node.js is multi-threaded.”</p><p>But if you take a deeper look at its architecture from a developer’s perspective, you can only conclude that Node.js is fundamentally <strong>single-threaded</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uHH0AoLZvbMwLufoiNgDg.png" /></figure><h3>1. The Core Model: A Perfect Collaboration with the OS</h3><p>Node.js operates with a <strong>single main thread</strong> that runs the event loop to process tasks.</p><p>For <strong>network I/O</strong>, like API calls or database queries, Node.js delegates the work to the operating system’s powerful asynchronous event mechanisms, such as epoll on Linux or IOCP on Windows.</p><p>It’s as if Node.js is telling the OS:</p><blockquote><em>“Hey OS, let me know when the result of that API or DB call is ready. Once it is, I’ll handle the rest with a callback function on my main thread!”</em></blockquote><p>Because the OS handles the asynchronous work and notifies Node.js upon completion, the main thread never needs to stop. It’s free to continue processing other tasks. This is the model everyone agrees on.</p><h3>2. Where the Confusion Begins: File I/O and the libuv Thread Pool</h3><p>The problem arises with tasks like <strong>file I/O</strong> or <strong>DNS lookups</strong>.</p><p>Unlike network I/O, operating systems don’t always provide a unified, non-blocking system for these tasks. To ensure consistent behavior across platforms, Node.js delegates this work to the <strong>libuv thread pool</strong>.</p><p>In this scenario, it’s as if the OS is telling Node.js:</p><blockquote><em>“Node, you’ll have to wait right here until I’ve finished reading this file for you.”</em></blockquote><p>In other words, it’s a <strong>blocking</strong> operation. So what happens if the main thread is blocked? A backend server would grind to a halt, unable to process any other requests. A browser would freeze, and user events like clicks would become completely unresponsive.</p><h3>3. The Solution: The libuv Thread Pool</h3><p>To solve this problem, Node.js uses libuv&#39;s thread pool. It offloads any potentially blocking tasks to a separate worker thread.</p><p>By default, this pool has four threads. When the main thread encounters a blocking function like file I/O, it says:</p><blockquote><em>“Whoa, blocking is scary! I’d better hand this off to the thread pool.”</em></blockquote><p>A worker thread from the pool then performs the blocking task — in this case, reading the file — while the main thread remains free. Once the task is complete, the result is sent back to the main thread to be processed.</p><p>This is where the “wordplay” that “Node.js is multi-threaded” comes from. While it’s true that the main thread where Node.js runs is single, there are multiple threads (the thread pool) collaborating behind the scenes.</p><h3>4. Why It’s Still ‘Single-Threaded’</h3><h4>The Developer’s Mindset is Strictly Single-Threaded</h4><p>The most important point is that as developers, we must code from the perspective of the <strong>main single thread</strong>. All the JavaScript we write is executed sequentially on this one thread.</p><p>The thread pool is merely a behind-the-scenes helper. We don’t control it or even think about its existence while coding. Instead, our primary concern is always, “How can I avoid blocking the main thread?” This is the core principle of Node.js development.</p><h4>The Definitive Proof: CPU-Bound Work</h4><p>The most undeniable proof that Node.js is single-threaded appears when it encounters a <strong>CPU-bound task</strong> (a heavy computation that uses a lot of CPU).</p><p>If you have a for loop that iterates a billion times inside a callback, that code isn&#39;t delegated to the thread pool. It takes over the <strong>main thread</strong> directly.</p><p>The moment that loop starts, the event loop stops, and the server becomes completely unresponsive to new requests. In contrast, a multi-threaded server like those built with Java or Python would handle a new request on a different thread, even while another is busy with a heavy calculation.</p><h3>Conclusion</h3><p>Node.js <strong>utilizes</strong> multiple threads to achieve its non-blocking model, but its programming paradigm is fundamentally <strong>single-threaded</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=738d9d937015" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>