<?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"><channel><title><![CDATA[Kigyou-list Tech Blog]]></title><description><![CDATA[Kigyou-list Tech Blog]]></description><link>https://kigyoulist.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 00:37:40 GMT</lastBuildDate><atom:link href="https://kigyoulist.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Scaling Japan's B2B Data Infrastructure: Modern ETL Architecture with Python & PostgreSQL for 5M Corporate Records]]></title><description><![CDATA[In Japan, there are currently over 5 million registered legal entities, including corporations, government agencies, and non-profit organizations. In B2B…]]></description><link>https://kigyoulist.hashnode.dev/scaling-japan-s-b2b-data-infrastructure-modern-etl-architecture-with-python-postgresql-for-5m-corporate-records</link><guid isPermaLink="true">https://kigyoulist.hashnode.dev/scaling-japan-s-b2b-data-infrastructure-modern-etl-architecture-with-python-postgresql-for-5m-corporate-records</guid><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Python]]></category><category><![CDATA[data-engineering]]></category><dc:creator><![CDATA[Kigyou-list Engineering | 株式会社ＴＱＣ]]></dc:creator><pubDate>Thu, 26 Nov 2026 09:44:57 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>In Japan, there are currently over 5 million registered legal entities, including corporations, government agencies, and non-profit organizations. In B2B sales development, credit risk management, KYC/compliance, and sales intelligence, verifying that a company is legally active, tracking relocation or trade name changes, and validating qualified invoice issuer status (インボイス適格請求書発行事業者) are critical requirements.</p>
<p>However, operating a real-time data sync pipeline against public open data sources presents several technical challenges:</p>
<ol>
<li><strong>National Tax Agency (NTA) Corporate Number Web-API</strong>: Emits tens of thousands of daily and monthly updates (new incorporations, trade name modifications, head office relocations, liquidations). Point-by-point HTTP requests quickly hit rate limits and latency bottlenecks.</li>
<li><strong>METI gBizINFO REST API</strong>: Provides rich financial, subsidy, procurement, and certification metadata, but responses have deeply nested schemas requiring complex normalization and entity matching.</li>
<li><strong>Database Write Throughput</strong>: Naive <code>UPDATE</code> statements on a 5,000,000-row PostgreSQL table cause severe index write amplification, WAL log bloat, and table locks.</li>
</ol>
<p>In this article, the engineering team at <strong><a href="https://kigyoulist.com/ja">Kigyou-list</a></strong> shares our production architecture and practical code for synchronizing and normalizing 5 million corporate records in sub-second latency using Python and PostgreSQL.</p>
<hr />
<h2>1. System Architecture Overview</h2>
<p>Our pipeline uses an event-driven staging architecture combining Python asynchronous stream processing with PostgreSQL set-based bulk upserts (<code>COPY</code> binary streams and <code>INSERT ... ON CONFLICT DO UPDATE</code>):</p>
<pre><code>+-----------------------------------+     +-----------------------------------+
|  National Tax Agency Web-API v4   |     |      METI gBizINFO REST API v2    |
+-----------------+-----------------+     +-----------------+-----------------+
                  | (Daily Diff Stream)                     | (Financial &amp; Subsidy)
                  v                                         v
        +---------+-----------------------------------------+---------+
        |                 Python ETL Ingestion Engine                 |
        |  - Modulus 9 Check Digit Pre-Validation                     |
        |  - Japanese Address &amp; Trade Name Normalization             |
        |  - Change Data Capture (CDC) Hash Calculation               |
        +-----------------------------+-------------------------------+
                                      |
                                      v (Binary COPY Stream)
        +-----------------------------+-------------------------------+
        |               PostgreSQL Unlogged Staging Table             |
        +-----------------------------+-------------------------------+
                                      |
                                      v (Set-based Atomic Bulk Upsert)
        +-----------------------------+-------------------------------+
        |           Master Corporate Table (5,000,000+ Records)       |
        |  - Trigger-based Historical Audit Logging                   |
        |  - Fast Trigram &amp; B-Tree Indexes                            |
        +-----------------------------+-------------------------------+
                                      |
                                      v (Sub-15ms Queries)
        +-----------------------------+-------------------------------+
        |          FastAPI High-Performance Search Engine             |
        |             Production: https://kigyoulist.com/ja           |
        +-------------------------------------------------------------+
</code></pre>
<hr />
<h2>2. Modulus 9 Check Digit Verification Algorithm</h2>
<p>Every Japanese Corporate Number (法人番号) consists of 13 digits. The leftmost digit (Position 13 from the right) is a calculated check digit, derived from the remaining 12 digits using a weighted modulus 9 algorithm defined by the National Tax Agency.</p>
<p>Validating this digit in the Python application layer before hitting downstream databases prevents invalid queries and rejects corrupt input in nanoseconds:</p>
<pre><code class="language-python">def verify_corporate_number(num_str: str) -&gt; bool:
    """
    Validates a 13-digit Japanese Corporate Number using the NTA Modulus 9 specification.
    Returns True if the leading check digit matches the calculated value.
    """
    if not num_str or len(num_str) != 13 or not num_str.isdigit():
        return False

    digits = [int(c) for c in num_str]
    check_digit = digits[0]
    sub_digits = digits[1:]  # 12 digits from P12 to P1

    # NTA weighting rule:
    # For n = 1 to 12 (from right to left), weight is 1 if n is odd, 2 if n is even.
    # In 0-indexed sub_digits (left to right), index i corresponds to n = 12 - i.
    total_sum = 0
    for i, d in enumerate(sub_digits):
        weight = 2 if (i % 2 == 0) else 1
        total_sum += d * weight

    remainder = total_sum % 9
    expected_check_digit = 9 - remainder

    return check_digit == expected_check_digit
</code></pre>
<hr />
<h2>3. High-Throughput Bulk Merge SQL Pattern</h2>
<p>Updating rows one by one in a 5M-row table causes disastrous performance drops. Instead, we load incoming records into an <code>UNLOGGED TEMP TABLE</code> via PostgreSQL's binary <code>COPY</code> protocol, then execute an atomic set-based merge:</p>
<pre><code class="language-sql">-- 1. Create a lightweight temporary staging table
CREATE TEMP TABLE tmp_corporate_diff (
    corporate_number CHAR(13) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    kind VARCHAR(10),
    full_address TEXT,
    postal_code VARCHAR(10),
    nta_updated_at DATE
) ON COMMIT DROP;

-- 2. Bulk stream data using psycopg3 binary copy (50,000 rows in &lt; 0.3s)
-- Python: cursor.copy("COPY tmp_corporate_diff FROM STDIN ...")

-- 3. Atomic set-based merge with IS DISTINCT FROM predicate
INSERT INTO master_corporations (
    corporate_number,
    corporate_name,
    kind,
    full_address,
    postal_code,
    nta_updated_at,
    updated_at
)
SELECT 
    corporate_number,
    name,
    kind,
    full_address,
    postal_code,
    nta_updated_at,
    CURRENT_TIMESTAMP
FROM tmp_corporate_diff
ON CONFLICT (corporate_number) DO UPDATE SET
    corporate_name  = EXCLUDED.corporate_name,
    kind            = EXCLUDED.kind,
    full_address    = EXCLUDED.full_address,
    postal_code     = EXCLUDED.postal_code,
    nta_updated_at  = EXCLUDED.nta_updated_at,
    updated_at      = CURRENT_TIMESTAMP
WHERE master_corporations.nta_updated_at IS DISTINCT FROM EXCLUDED.nta_updated_at;
</code></pre>
<blockquote>
<p><strong>Performance Note</strong>: The <code>WHERE master_corporations.nta_updated_at IS DISTINCT FROM EXCLUDED.nta_updated_at</code> clause skips write locks and WAL emission for unchanged rows, yielding an ~8x throughput boost.</p>
</blockquote>
<hr />
<h2>4. Production Benchmarks &amp; Verification</h2>
<p>By deploying this pipeline to our production infrastructure, we achieved substantial performance improvements:</p>
<table>
<thead>
<tr>
<th align="left">Metric</th>
<th align="left">Sequential Processing</th>
<th align="left">Modern Bulk ETL Pipeline</th>
<th align="left">Improvement Factor</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><strong>Daily Diff Synchronization (~5,000 companies)</strong></td>
<td align="left">18 min 42 sec</td>
<td align="left"><strong>2.8 sec</strong></td>
<td align="left"><strong>~400x faster</strong></td>
</tr>
<tr>
<td align="left"><strong>Full 5M Initial Ingestion</strong></td>
<td align="left">32 hours</td>
<td align="left"><strong>44.5 min</strong></td>
<td align="left"><strong>~43x faster</strong></td>
</tr>
<tr>
<td align="left"><strong>Check Digit Accuracy</strong></td>
<td align="left">Unenforced</td>
<td align="left"><strong>100% Guaranteed</strong></td>
<td align="left">Zero bad writes</td>
</tr>
<tr>
<td align="left"><strong>Database Server CPU Utilization</strong></td>
<td align="left">85% - 98% (spiky)</td>
<td align="left"><strong>14% (stable)</strong></td>
<td align="left"><strong>83% resource reduction</strong></td>
</tr>
</tbody></table>
<hr />
<h2>5. Live Production Platform &amp; Resources</h2>
<p>This architecture powers our live production platforms, providing real-time queries across Japan's corporate landscape:</p>
<ul>
<li><strong>Corporate Master Database Hub</strong>:<br /><a href="https://kigyoulist.com/ja">Kigyou-list Corporate Master Database (5M+ Companies)</a></li>
<li><strong>Qualified Invoice Issuer Lookup</strong>:<br /><a href="https://kigyoulist.com/ja/invoice">Invoice Registration Number Real-Time Search &amp; Verification</a></li>
<li><strong>Feature &amp; Pricing Matrix (No Annual Lock-in)</strong>:<br /><a href="https://kigyoulist.com/ja/compare">B2B Data Pricing &amp; Feature Comparison</a></li>
<li><strong>High-Speed Query Engine</strong>:<br /><a href="https://kigyoulist.com/ja/search">High-Speed Corporate Search Engine</a></li>
</ul>
<hr />
<h2>Conclusion</h2>
<p>Building resilient, high-speed corporate data pipelines requires disciplined separation of concerns: pre-validating mathematical check digits at the application layer, leveraging unlogged staging tables for binary ingestion, and executing set-based atomic merges in PostgreSQL. This architecture ensures high availability, strict data integrity, and blazing-fast query response times at scale.</p>
]]></content:encoded></item></channel></rss>