October 15, 2026

The Program Is the Data Layout: Taking a COBOL System to Rust

COBOL logic is usually simple. The hard part is the data: packed decimals, implied decimal points, EBCDIC text and arithmetic that cuts off digits instead of rounding. Here's how we list what a COBOL system really does, run Rust next to it one job step at a time, get every cent to match, and prove it byte for byte, using a real COBOL banking system we moved to Rust.

The Program Is the Data Layout: Taking a COBOL System to Rust

Our last few posts moved front ends from one framework to another. This one goes much further back. COBOL is older than most of the people who still maintain it, and it still runs a lot of payroll, banking and insurance systems. Many teams want to leave it. Fewer people know it each year, mainframe time is expensive, and every change takes longer than it should.

Rust is a good place to land. It's fast, and it has no garbage collector to pause a batch job halfway. Its type system catches whole kinds of mistakes before the code runs. But what surprised us most was this: the hard part isn't the COBOL logic. COBOL logic is usually simple. The hard part is the data. In COBOL, a record is just a run of bytes, and the copybook that describes those bytes is the real contract between every program that reads them. Get the layout or the arithmetic slightly wrong and nothing crashes. The totals are just off by a cent.

The example: every snippet in this post comes from a real program you can run: Banco-en-COBOL, an open-source banking system written in GnuCOBOL, and our Rust rewrite of it. It has customers, accounts, transfers and cards, all kept in six fixed-length files, plus INTERESES, a small monthly interest job we added so the example covers batch work too. Both versions are in cobuild-tech/migratex-examples. Banco runs on GnuCOBOL with plain ASCII files, so where a mainframe adds packed decimals or EBCDIC, we say so.

Before You Start

Before you start: list every program, copybook, JCL job, file and transaction. Write down the hidden rules in the data, such as packed decimals, implied decimal points, REDEFINES and EBCDIC. Then save real input and output files from production to compare against later

Should you move at all?

Be honest about this one. A COBOL system that's been running for thirty years has thirty years of bug fixes in it, and many of them aren't written down anywhere else. If the system is stable, rarely changes and the cost is fine, leaving it alone is a perfectly good answer. Wrapping it in an API can buy you years.

Move when the code is holding you back. That might be because nobody left can change it safely, because a simple change takes a whole quarter, or because the mainframe bill keeps growing. And move in pieces. Big-bang rewrites of core systems have a poor record, and the larger the system, the worse it gets.

Make a list of everything that runs

A COBOL system is much more than its .cbl files. Before you estimate anything, list:

  • Programs, and which ones CALL each other.
  • Copybooks, and which programs include each one. A copybook used by forty programs is a contract you can't change lightly.
  • JCL jobs: the order steps run in, which files each step reads and writes, and what happens when a step fails.
  • Files and tables: sequential files, VSAM files and DB2 tables, and who owns each one.
  • CICS transactions, if there are online screens as well as batch jobs.
  • The schedule: what runs nightly, monthly and at year end. Year-end jobs are easy to miss because they ran once, eleven months ago.

Write down what the data is hiding

Most of the risk lives in the copybooks, the record layouts every program shares. This is Banco's account record:

       01 REGISTRO-CUENTA.
           05 RCU-ID            PIC 9(10).
           05 RCU-CLIENTE-ID    PIC 9(8).
           05 RCU-IBAN          PIC X(24).
           05 RCU-SALDO         PIC 9(12)V99.
           05 RCU-TIPO          PIC X(20).
           05 RCU-FECHA-APERTURA PIC X(10).
           05 RCU-FECHA-CIERRE  PIC X(10).
           05 RCU-ESTADO        PIC X(1).
           05 RCU-LIMITE-DIARIO PIC 9(10)V99.
           05 RCU-LIMITE-MENSUAL PIC 9(10)V99.
           05 RCU-COMISION      PIC 9(3)V999.
           05 RCU-RELLENO       PIC X(50).

Every line carries a rule that isn't visible in the code that uses it. RCU-SALDO holds 825.50 as the digits 00000000082550: the point is implied by the V, and never stored. Banco keeps its numbers as plain digits. On a mainframe, the same fields would usually be COMP-3. Here are the rules we check for in every copybook:

What to look forWhat it meansWhy it matters in Rust
V in a PICAn implied decimal point. S9(7)V99 stores 123456 for 1,234.56The point is never stored. You add it back when you read the field
COMP-3Packed decimal: two digits per byte, with the sign in the last half-byteYou need a decoder. A 9-digit field takes 5 bytes
PIC X textUsually EBCDIC on a mainframe, not ASCIIText has to be converted, but packed fields must never be
REDEFINESTwo layouts for the same bytes. Another field decides which one appliesBecomes a Rust enum, and you need to find the field that decides
OCCURS DEPENDING ONA table whose length is set by another field in the recordRecords have different lengths, so you can't just read fixed-size chunks
88 levelsNamed values for a field, like ACCT-SAVINGSBecome enum variants. Values with no name still turn up in real data
Arithmetic without ROUNDEDExtra decimal places are cut off, not roundedRust code that rounds will be wrong by a cent, again and again

Save real files before you change anything

This is the most useful thing you can do, and it costs very little. For each job you plan to move, save a real night's input files and the output the COBOL job produced from them. Mask the personal data if you need to, but keep the odd records: the negative balances, the empty names, the account types nobody remembers adding. These are your golden files. Later, the Rust version passes only when it turns the same input into exactly the same bytes.

Running COBOL and Rust Together

Running COBOL and Rust together: the JCL job keeps running, and one step at a time is replaced by a Rust program that reads and writes the same files in the same layout. Both versions run on the same input, and a compare step checks their output byte for byte, until every step is Rust

As with the front-end moves, we don't replace everything at once. We replace one piece at a time, while the rest keeps running. Martin Fowler calls this the strangler fig pattern. In a batch system, the natural piece is a job step. Each step reads some files and writes others, so if a Rust program reads and writes exactly the same files, the steps around it can't tell it changed.

Where does Rust run?

Rust doesn't build programs for z/OS itself, but it does support Linux on IBM Z (s390x-unknown-linux-gnu). So you can run the new code on the same machine, in a Linux partition, close to the data. The other option is to move the files off the mainframe and run everything on ordinary servers. Either works. Choose based on where the data needs to end up, not where the code is easiest to run.

Read the same bytes

The first piece of Rust you write isn't business logic. It's a reader for the copybook. On a mainframe file, that starts with a decoder for packed decimal fields. Here's one, using rust_decimal so money never touches a float:

use rust_decimal::Decimal;

/// Decode a COMP-3 field, e.g. PIC S9(7)V99 COMP-3 is 5 bytes, scale 2.
pub fn unpack_comp3(bytes: &[u8], scale: u32) -> Result<Decimal, DecodeError> {
    let (last, rest) = bytes.split_last().ok_or(DecodeError::Empty)?;
    let mut n: i64 = 0;
    for &b in rest {
        n = n * 100 + digit(b >> 4)? as i64 * 10 + digit(b & 0x0F)? as i64;
    }
    n = n * 10 + digit(last >> 4)? as i64;
    match last & 0x0F {
        0x0C | 0x0F => Ok(Decimal::new(n, scale)),  // C = positive, F = unsigned
        0x0D => Ok(Decimal::new(-n, scale)),        // D = negative
        s => Err(DecodeError::BadSign(s)),
    }
}

fn digit(nibble: u8) -> Result<u8, DecodeError> {
    if nibble <= 9 { Ok(nibble) } else { Err(DecodeError::BadDigit(nibble)) }
}

Return an error for a bad nibble. Don't guess. Old files often contain records where a packed field holds spaces or junk, and the COBOL program may have quietly skipped them (or crashed on them, with an operator who knows to restart the job). You want to see those records, not turn them into zero.

Then build the record type from the copybook. This is Banco's account record in the port, with the trait every record type implements:

pub trait Record: Sized {
    const FILE: &'static str;
    const LEN: usize;
    fn decode(bytes: &[u8]) -> Self;
    fn encode(&self) -> Vec<u8>;
}

pub struct Cuenta {
    pub id: u64,
    pub cliente_id: u64,
    pub iban: Text<24>,
    pub saldo: u64,
    pub tipo: Text<20>,
    // … dates, state, limits and commission, in copybook order
}

Three details are worth copying. First, text stays as bytes. Text<24> is just [u8; 24], so trailing spaces and accented letters go back out exactly as they came in. Second, saldo is a whole number of cents, never a float. Third, nothing is guessed: an account type the program doesn't know is kept as it is, so it can be written back unchanged. Real data always has values nobody named. On a mainframe file, also decode EBCDIC with a table for the right code page, usually 037 in the US or 1140 if you need the euro sign. Convert only the PIC X fields. Running the whole record through a text converter destroys every packed field in it.

Write the encoder too, and test that decoding then encoding a record gives back the same bytes, for every record in the golden files. The Banco port does this for all six of its layouts. Until that passes, don't write any business logic.

Run both and compare

In the JCL, add a step that runs the Rust version on the same input and writes to a separate file, then a final step that compares the two outputs. The COBOL output still goes downstream. The Rust output just gets checked. Run it like this every night for a few weeks. Real data will find cases your tests didn't. When the outputs have matched for long enough, swap which one goes downstream, and keep the COBOL step around for a while in case you need to switch back. With Banco, we also let the two take turns on one set of files: COBOL, then Rust, then COBOL, then Rust. The files still came out identical to an all-COBOL run, which shows that the steps around a replaced one can't tell.

Getting the Numbers Right

Getting the numbers right: COBOL fixed-point decimals become rust_decimal values, never floats. Results without ROUNDED are truncated, ROUNDED rounds half away from zero, and a result too big for its field is caught with ON SIZE ERROR or silently loses its leading digits

Here's the line at the heart of INTERESES:

      * No ROUNDED: COBOL cuts the extra decimals off.
           COMPUTE WS-INTERES = RCU-SALDO * WS-TASA / 100 / 12
           IF WS-INTERES > 0
               MOVE RCU-SALDO        TO WS-SALDO-ANTERIOR
               ADD WS-INTERES        TO RCU-SALDO

It looks simple, and it hides three rules.

Never use floats

f64 can't hold 0.10 exactly, and the errors add up across millions of accounts. COBOL's PIC 9V99 is exact decimal arithmetic, so the Rust has to be exact too. rust_decimal stores up to 28 significant digits, which covers any field you'll meet in practice, and it gives you control over how results are rounded.

Truncate unless COBOL says ROUNDED

WS-INTERES is PIC 9(12)V99. The calculation produces more decimal places than that, and because there's no ROUNDED, COBOL simply cuts off the extra digits. A month's interest on 1,000.00 at 0.5% a year is 0.41666…, and GnuCOBOL posts 0.41, not 0.42. Most Rust code rounds by habit, and that's how you end up one cent away on a third of your accounts. In the port, the rule lives in one place, so nobody can forget it:

/// Stores a result the way `MOVE`, `ADD`, `SUBTRACT` and `COMPUTE` do with
/// no `ROUNDED` and no `ON SIZE ERROR`: an unsigned field drops the sign,
/// and digits that don't fit on the left are cut off. `ADD 1` to a
/// `PIC 99` holding 99 gives 0.
pub fn store(self, value: i128) -> u64 {
    (value.unsigned_abs() % 10u128.pow(self.int + self.scale)) as u64
}

/// `COMPUTE WS-INTERES = RCU-SALDO * WS-TASA / 100 / 12` into `PIC 9(12)V99`.
pub fn interes_mensual(saldo: u64, tasa: u64) -> u64 {
    SALDO.store((u128::from(saldo) * u128::from(tasa) / 1_200_000) as i128)
}

The balance is a count of cents and the rate a count of thousandths of a percent, so whole-number division does the truncating for free. Banco's fields are all unsigned and none are packed, so whole numbers were enough. For signed or packed fields, rust_decimal gives you the same rule with RoundingStrategy::ToZero, and RoundingStrategy::MidpointAwayFromZero matches COBOL's ROUNDED.

Decide what happens when a number doesn't fit

If a result is too big for its field and there's no ON SIZE ERROR, the COBOL standard doesn't say what the field should hold. In practice, compilers drop the leading digits. On GnuCOBOL, ADD 1 to a PIC 99 holding 99 gives 00, and IBM's compiler does the same for decimal fields. Banco never codes ON SIZE ERROR, so a deposit that takes a balance past 999,999,999,999.99 quietly loses its leading digits. The port copies that, because it has to match the original, and lists it as a known risk. In your own migration, search for arithmetic without ON SIZE ERROR and decide each case on purpose. Returning an error is almost always what you want, but it's a change in behaviour, and the golden files will tell you if the old behaviour ever happened.

Numbers typed in have rules too

Banco reads amounts from the keyboard with ACCEPT, and GnuCOBOL's rules for turning text into a number are generous. Commas are skipped, so 7,25 becomes 725.00. That's a real risk in Spain, where the comma is the decimal point. A minus sign is dropped, so -5 becomes 5. And 12a is 12 in an 8-digit id field but 0 in an amount field. None of this is in the program's source. It lives in the COBOL runtime. We copied the rules from the GnuCOBOL source, then checked the Rust version against COBOL on 1,550 inputs, for every kind of number field the program reads.

Expect small differences in the middle of a sum

COBOL compilers keep intermediate results at a precision that depends on the compiler, its options and the fields involved. rust_decimal keeps up to 28 digits. Most of the time the final answer is the same. Sometimes a long division gives a different last digit before truncation, and you see a one-cent difference on a few accounts. This is exactly why the golden files matter. When you find a difference, work out the exact steps COBOL takes, write them out in Rust, and add the record that showed it to your tests.

COBOLRust
PIC 9(12)V99 (unsigned, plain digits)A whole number of cents, as in the Banco port
PIC S9(7)V99 COMP-3Decimal, checked against 7 digits before the point and 2 after
COMPUTE X = … (no ROUNDED)round_dp_with_strategy(dp, RoundingStrategy::ToZero)
COMPUTE X ROUNDED = …RoundingStrategy::MidpointAwayFromZero
ON SIZE ERRORResult with a SizeError
No ON SIZE ERRORLeading digits dropped. Decide on purpose whether to copy that
PIC 9(8) dates like 20261015Parse into a real date type at the edge, write back as 8 digits

From Paragraphs to Functions

From paragraphs to functions: shared WORKING-STORAGE becomes structs passed to functions, PERFORM becomes a function call, GO TO becomes early returns and loops, file status codes become Result values, and DB2 and CICS calls become a database library and services

With the data and the arithmetic settled, the logic itself is the easy part. Most COBOL programs follow the same shape: open the files, read a record, process it, write it, repeat, close the files.

WORKING-STORAGE is one big global

Every paragraph in a COBOL program can read and change every variable in WORKING-STORAGE. So when you turn a paragraph into a function, the first job is to find what it really reads and writes. Make those the parameters and the return value. Totals and counters go into a small struct you pass along. Flags that only tell the next paragraph what to do usually disappear, replaced by a return value.

But do that tidying after the port matches, not during it. Banco shows why. Its customer menu, admin menu and main menu all loop on one flag, WS-MOSTRAR-MENU. Choosing "0. Cerrar Sesion" sets it to "N", the main menu sees the same "N", and the whole program closes instead of going back. A port that turned each flag into a local variable would have quietly fixed that, and nobody would have decided to. So the Banco port keeps WORKING-STORAGE as fields on one struct, and each paragraph as a method with the paragraph's name. Here is the batch loop from INTERESES and its Rust version:

       ABONAR-INTERESES.
           OPEN I-O CUENTAS-FILE
           OPEN EXTEND MOVIMIENTOS-FILE
           PERFORM UNTIL 1 = 0
               READ CUENTAS-FILE
                   AT END
                       EXIT PERFORM
                   NOT AT END
                       ADD 1 TO WS-CUENTAS-LEIDAS
                       IF RCU-ESTADO = "A"
                           PERFORM ABONAR-CUENTA
                       END-IF
               END-READ
           END-PERFORM
           CLOSE MOVIMIENTOS-FILE
           CLOSE CUENTAS-FILE.
let mut cuentas = files.read::<Cuenta>()?;
for c in cuentas.iter_mut() {
    leidas = CONTADOR.store(leidas as i128 + 1);
    if c.estado != *b"A" {
        continue;
    }
    // ABONAR-CUENTA: the rate for the account type, interes_mensual,
    // the new balance and a movement record
}
files.replace(&cuentas)?;

Keep the business rules (interes_mensual) as plain functions that take values and return values, with no files involved. They're easy to test, and they're the part your team will keep changing for years.

GO TO and fall-through

Older programs use GO TO and PERFORM THRU, which runs a range of paragraphs one after another. Before you translate them, draw out where control can actually go. Usually it's a loop with a few early exits, which becomes a loop with continue or an early return. If a paragraph is never reached, check the JCL and other programs before deleting it, but it really is often dead code.

File status codes become errors

COBOL reports file problems through a two-character status: 00 is fine, 10 is end of file, 23 is record not found, and so on. Programs check it (or forget to) after each read. In Rust these become a Result, and the end of file becomes the end of a loop, as above. Be careful with programs that ignore a status. Find out what they did next, because downstream jobs may depend on it. Banco never checks one: it opens every file at start-up and stops with status 35 if one is missing. The port creates the missing files instead, and its notes say so.

DB2 and CICS

Embedded EXEC SQL usually maps directly to a Rust database library such as sqlx, and the SQL itself often moves over nearly unchanged. Watch for COMMIT placement: batch jobs often commit every few thousand records so they can restart halfway, and your Rust job needs the same restart point. CICS online transactions are a bigger piece of work. Each one is a request and a response, so it usually becomes an HTTP endpoint, and the 3270 screen becomes a web page. Plan those as their own project after the batch side is stable.

What the Move Found

Banco is small, about 1,600 lines, and reading it closely still turned up more than a dozen problems. Some of the worst:

  • Every account gets the same IBAN. The IBAN is built with STRING ... DELIMITED BY SPACE from a PIC Z(10) field. Zero suppression fills the front of that field with spaces, so the STRING stops before the number. Every account is ES910000000000, and a transfer by IBAN always lands in the oldest account in the bank.
  • Logging out closes the program, because of the shared menu flag above.
  • Ids start again on every run. The counters only ever start from their VALUE clause, so after a restart the next customer is 1001 again, next to the first 1001. Logging in as 1001 then opens the first one's accounts.
  • Received transfers are filed under the sender, so they never show in the receiver's history.
  • Any customer can block or re-PIN any card, and a deleted customer can still log in.
  • Backup and restore do nothing except print that they worked.

A port that keeps these bugs is no use. But a port that fixes them as it goes can't be compared with the original, and that comparison is the whole safety net. So the Rust version has two modes. With BANCO_COMPAT=1, it reproduces the original exactly, bugs included, and that's what the golden tests run. The default mode fixes nine of the bugs. Each fix is one if self.fixed() in the code, with a comment saying what the original did and a test that fails in compat mode. The port matched every recording in compat mode first. Only then were the fixes added, one at a time.

Some things we found and left alone, because changing them is a business decision, not a migration one: the daily and monthly limits that are stored but never checked, and the comma that turns 7,25 into 725.00. They're listed in the example's README, so the decision is written down rather than forgotten.

Testing the Migration

Testing the migration: the same golden input files go to the COBOL job and the Rust job, and the outputs are compared byte for byte. Unit tests cover the decoders and business rules, and property tests compare the Rust arithmetic against a reference over thousands of random values

Old COBOL systems rarely have automated tests. What they do have is decades of real input and output, and that's better than tests written from memory.

  • Golden files. For each job, the saved inputs go through the Rust version, and the output has to match the saved COBOL output byte for byte. Any difference fails the build and shows the line or file that differs. Banco had no production data, so we recorded sessions instead: ten scripted sessions, some across several runs of the program, typed into the COBOL build. The screen output and all six data files were saved after each of the 19 runs, and the Rust port has to match every byte. These tests run on every change.
  • A fixed clock. Dates, times and even Banco's card PINs come from the clock. GnuCOBOL lets you pin it with COB_CURRENT_DATE, and the port reads the same variable, so both sides see the same moment.
  • Round trips. Every record layout decodes and encodes back to the same bytes. This catches layout mistakes before they can look like logic bugs.
  • Unit tests for the business rules, written as plain values in and values out, like interes_mensual(123457, 2500) == 257. Add every odd record you find in production here, with a comment saying where it came from.
  • Many inputs for the tricky rules. For Banco, 1,550 inputs (the awkward cases plus random strings) go through COBOL's ACCEPT and through the Rust parser, and every result has to match. A property testing tool such as proptest can generate cases like these for the arithmetic too, and check that store always truncates and never rounds unless asked.
  • The nightly parallel run. This is the final test, and it uses real data. Nothing is moved until it has matched for an agreed number of nights, including a month end.

A non-mainframe COBOL compiler such as GnuCOBOL is what made the Banco recordings possible. It builds the original unchanged, so we could run it as often as we liked and record new golden files whenever a session changed. On a real mainframe system, treat its results with care. Its defaults for things like intermediate precision and binary fields can differ from IBM's, so check them against real mainframe output before you trust them.

Finishing the Migration

Finishing the migration: every job step runs in Rust, parallel runs have matched through a month end and a year end, the COBOL steps are removed from the JCL, the copybooks become Rust types with a written specification, and the rollback path is kept until the first quiet quarter is over

A job is done when its Rust version has sent output downstream through at least one month end without a difference, and you've switched off the COBOL version. Then work through the clean-up:

  1. Remove the COBOL steps and the compare steps from the JCL, or move the whole job to your new scheduler.
  2. Keep the COBOL load modules and the last golden files for a quarter, so you can switch back if a year-end case turns up.
  3. Decide where the data lives now. While any COBOL program still reads a file, keep its layout exactly as it is. Once the last one is gone, you're free to move to a modern format, and to stop using EBCDIC.
  4. Write the copybook rules down. Those Rust record types are now the only description of the data. Add a short page that explains each field, including the odd values you found.
  5. Watch the first year end closely. Some jobs only run once a year, and some code paths only run then too.

Take it one job at a time, and the whole system moves without one big, risky weekend.

About MigrateX

MigrateX

MigrateX is our platform and service for moving software, data and infrastructure from one technology to another. It combines automation with experienced engineers. The automation does the repetitive work quickly, and the engineers make the tricky decisions.

This guide is how we approach COBOL to Rust projects with MigrateX. Here's what that looks like:

  1. Assessment. We list every program, copybook, job, file and transaction, and every hidden rule in the data: packed decimals, implied decimal points, REDEFINES and truncating arithmetic. You see where the work is before anyone agrees on a timeline.
  2. Plan. We work with your team to decide which jobs move first, where the new code runs, and which old behaviour to keep exactly and which to fix on purpose.
  3. Migration, step by step. Automation handles the repetitive parts, like turning copybooks into Rust types and decoders. Our engineers handle the parts that need thought, like arithmetic, control flow and restart points.
  4. Proof that it works. We save real input and output from production and run both versions side by side. A job only counts as moved when its output matches byte for byte.
  5. Handover and clean-up. We remove the old steps, keep a way to switch back through the year end, and leave your team with a Rust codebase they understand and own.

What you get along the way:

  • No big switch-over weekend. Your batch jobs keep running every night while the move happens one step at a time.
  • Less risk. Byte-for-byte comparisons and a way to switch back mean nobody downstream notices the change.
  • A team that's ready. We work alongside your developers the whole time, including the people who know the COBOL, so the knowledge moves with the code.
  • More than one kind of move. We use the same approach for front ends like Angular, Ember and jQuery, and for data and infrastructure moves too.

To see the code behind this guide, visit github.com/cobuild-tech/migratex-examples. Got a COBOL system that everyone is afraid to touch? We'd love to hear about it. Tell us a little about it through Contact Us, and we'll start with a free chat about where the work is likely to be.

References

Migration strategy

  1. M. Fowler. StranglerFigApplication. martinfowler.com, 29 June 2004. https://martinfowler.com/bliki/StranglerFigApplication.html
  2. M. Feathers. Working Effectively with Legacy Code. Prentice Hall, 2004.

COBOL

  1. IBM. Enterprise COBOL for z/OS documentation. https://www.ibm.com/docs/en/cobol-zos
  2. GnuCOBOL. https://gnucobol.sourceforge.io/
  3. Mel-Roses. Banco-en-COBOL: a banking management system written in GnuCOBOL. AGPL-3.0. https://github.com/Mel-Roses/Banco-en-COBOL
  4. CobuildX AI. migratex-examples: Banco-en-COBOL and its Rust rewrite, with golden sessions recorded from GnuCOBOL. https://github.com/cobuild-tech/migratex-examples/tree/main/cobol-rust