SONiC Capabilities: Empowering Networks with Open-Source Solutions

Download PDF

YANG Model: A Data Modeling Approach to Network Management

October 30, 2026

Key takeaways:

  • A YANG model is a schema for a network device: it defines which configuration and state data exist, their types, their keys, and the rules a valid change has to follow.
  • NETCONF, RESTCONF, and gNMI all carry YANG-modeled data; the protocol changes the transport and encoding, and the model stays the same.
  • Validating a change against the model before it reaches a switch catches a dangling VLAN reference, a value out of range, or two settings that conflict, each with an exact path to the bad field.
  • SONiC models its own CONFIG_DB tables in YANG (143 sonic-*.yang modules on the master branch in October 2026), and its patch tool refuses changes to any table that has no model, while everyday config commands skip it by default.

Your automation pushes a VLAN change to 40 leaf switches, every job reports success, and one server port now carries an access VLAN and a trunk VLAN list, which your fabric design forbids. The template that generated the change had no way to know that rule, because it produced text, and text has no rules.

A YANG model is where those rules live. It describes a device’s configuration and state as typed, keyed, constrained data, so a tool can reject a bad change before any switch sees it.

This guide walks through a YANG model example you can compile, the errors it catches, and how SONiC uses YANG for its own configuration database.

Work with the SONiC Experts

Benefit from PLVision's deep experience delivering enterprise SONiC solutions across industries.

What Is a YANG Model and What Does It Describe?

YANG is a data modeling language standardized by the IETF. Version 1.0 was published as RFC 6020 in October 2010, and YANG 1.1 followed as RFC 7950 in August 2016; SONiC’s sonic-port and sonic-vlan models, for example, declare yang-version 1.1.

A YANG model describes four kinds of things on a device. Configuration data is what you write, such as a VLAN ID or an interface MTU, and state data is what you only read, such as counters, oper-status, and learned routes.

The same split now reaches optical gear, where coherent transceivers report line telemetry over gNMI through OpenConfig models, a direction traced in SONiC in optical infrastructure.

The other two are operations and events: remote procedure calls (RPCs) and actions you trigger, such as a reboot, and notifications the device emits, such as a link going down. A management tool can tell from the model alone which fields it may set and which it may only watch.

The model is a schema, so it never holds values itself. The values sit in a separate instance document (XML or JSON) that conforms to the schema. Take a simple network data model example: a YANG model for VLANs says a VLAN ID is an integer from 1 to 4094, and the instance says your fabric uses VLAN 100 and VLAN 200.

Where YANG Sits Between Protocols, Encodings, and Devices

YANG defines the shape of the data and stops there. Three protocols commonly move YANG-modeled data between a management system and a device, and each one picks its own transport and encoding.

Protocol Standard Transport Common encoding Typical use
NETCONF RFC 6241 (2011) SSH, port 830 XML Transactional configuration, with an optional candidate datastore
RESTCONF RFC 8040 (2017) HTTPS JSON or XML Configuration and reads from web tooling and scripts
gNMI OpenConfig specification gRPC over HTTP/2 Protobuf, JSON_IETF Streaming telemetry and configuration at fabric scale

Each protocol in the table reads and writes paths defined by the same YANG data models. That is why one model can serve a NETCONF config push today and a gNMI telemetry subscription tomorrow.

Laid side by side, the three protocols all lead back to the same model.

YANG model diagram: one schema of types, keys, and rules reaches a switch through three protocols, NETCONF over SSH with XML, RESTCONF over HTTPS with JSON or XML, and gNMI over gRPC.

The history behind these protocols, from SNMP polling to streaming telemetry, is told in From SNMP to gNMI. For modeling, switching protocols leaves your YANG work intact.

The YANG Language Building Blocks

The YANG language is built from statements, and a few of them do most of the work in any module. The table maps each common statement to what it models and to a networking example.

Statement What it models Networking example
module, namespace, prefix One named model and its unique identity ietf-interfaces, openconfig-bgp
import Reuse of types and nodes from another module Importing ietf-inet-types for IP addresses
revision A dated version of the module revision 2025-12-22
container A group of related nodes with no key interfaces, vlans
list with key Repeating entries identified by a key One entry per interface, keyed by name
leaf One typed value with no children mtu, enabled, description
leaf-list An ordered or unordered set of values Trunk VLANs on a port, DNS servers
typedef A named, restricted type vlan-id as uint16 from 1 to 4094
grouping and uses A reusable block of nodes A counters block reused under every port
augment Nodes added to another module’s tree Vendor-specific fields under a standard interface
must and when XPath rules a valid instance has to satisfy An MTU that has to exceed a tunnel overhead
config false State data that can be read, never written Octet counters and oper-status

The YANG leaf carries the actual values in every model, and everything above it in the tree exists to group, key, and constrain leaves.

Vendor gear adds one more: a deviation statement documents where a device’s implementation differs from a published model.

A YANG Model Example, Line by Line

The module below models VLANs and the ports that use them on a leaf switch. It compiles under pyang –strict against ietf-yang-types from the current IETF standard, and every validation result later in this guide comes from it.

The Module Header and Reusable Types

The header names the module, gives it a namespace and a short prefix, and imports the IETF common types for the 64-bit counters.

                    
                        
module example-vlans {
     yang-version 1.1;
     namespace "urn:example:vlans";
     prefix exv;
 
     import ietf-yang-types {
     prefix yang;
}
 
revision 2026-10-19 {
     description "Initial revision.";
}
 
typedef vlan-id {
     type uint16 {
       range "1..4094";
     }
}
 
grouping port-counters {
     leaf in-octets {
       type yang:counter64;
       config false;
     }
     leaf out-octets {
       type yang:counter64;
       config false;
     }
}

The typedef gives VLAN IDs one definition, so every place that stores a VLAN ID inherits the 802.1Q range. The grouping declares two counters as config false, which marks them as state the device reports and a client can never write.

Containers, Lists, and Leaves

The data tree holds a list of VLANs keyed by ID and a list of ports keyed by name. Each port points at VLANs instead of copying their IDs.

                    
                        
container vlans {
     list vlan {
       key "id";
       leaf id { type vlan-id; }
       leaf name { type string { length "1..32"; } }
       leaf mtu {
         type uint16 { range "1280..9216"; }
         default "9100";
       }
     }
}
 
container ports {
     list port {
       key "name";
       leaf name { type string; }
       leaf enabled { type boolean; default "true"; }
       leaf access-vlan {
         type leafref { path "/exv:vlans/exv:vlan/exv:id"; }
       }
       leaf-list trunk-vlans {
         type leafref { path "/exv:vlans/exv:vlan/exv:id"; }
         must "not(../access-vlan)" {
           error-message "Pick access-vlan or trunk-vlans for each port.";
         }
       }
       container statistics {
         uses port-counters;
       }
     }
   }
}

The leafref type catches a whole class of broken VLAN changes. It says an access VLAN has to be the ID of a VLAN that already exists in the vlans list, so a typo in a VLAN number fails validation instead of creating a port that forwards nothing.

Constraints That Catch Bad Configuration

The must statement on trunk-vlans encodes the design rule from the opening scenario. In this fabric a port carries an access VLAN or a trunk list, and the XPath expression not(../access-vlan) rejects any instance that sets both.

Production models often use when instead: OpenConfig’s openconfig-vlan sets an interface-mode leaf to ACCESS or TRUNK, and when statements expose access-vlan only in ACCESS mode and trunk-vlans and native-vlan only in TRUNK mode, so a trunk keeps its untagged native VLAN.

Ranges, lengths, and defaults work like the must rule: the MTU leaf accepts 1280 to 9216 bytes and falls back to 9100 when the instance leaves it out. Every one of these rules travels with the model, so any tool that loads it enforces the same limits.

Reading a YANG Tree Diagram

Reading a long module statement by statement is slow, so the YANG community uses a compact tree format, standardized in RFC 8340 (2018), that gives a one-screen view of the data model network engineers can review at a glance. Running pyang -f tree example-vlans.yang prints this for the module above:

                    
                        
module: example-vlans
   +--rw vlans
   |  +--rw vlan* [id]
   |     +--rw id      vlan-id
   |     +--rw name?   string
   |     +--rw mtu?    uint16
   +--rw ports
      +--rw port* [name]
         +--rw name           string
         +--rw enabled?       boolean
         +--rw access-vlan?   -> /vlans/vlan/id
         +--rw trunk-vlans*   -> /vlans/vlan/id
         +--rw statistics
            +--ro in-octets?    yang:counter64
            +--ro out-octets?   yang:counter64

The table decodes the symbols in this output.

Symbol Meaning In the example
rw Configuration you can read and write vlans, mtu, access-vlan
ro State data you can only read in-octets, out-octets
* after a name A list or leaf-list with many entries vlan*, trunk-vlans*
[id] The list’s key VLANs keyed by id
? after a name An optional leaf name?, mtu?
-> A leafref pointing at another node access-vlan points at /vlans/vlan/id

Tree output is also a quick way to compare two revisions of a module, because a renamed leaf or a new key shows up as a one-line difference. It omits ranges, patterns, and must rules, so diff the source for those.

A YANG Data Model Example: Valid and Invalid Instances

YANG data modeling pays off when a model validates real data. The JSON instance below follows the encoding in RFC 7951 (2016), where each top-level node is prefixed with its module name.

                    
                        
{
   "example-vlans:vlans": {
     "vlan": [
       {"id": 100, "name": "web-tier", "mtu": 9100},
       {"id": 200, "name": "storage"}
     ]
   },
   "example-vlans:ports": {
     "port": [
       {"name": "Ethernet0", "access-vlan": 100},
       {"name": "Ethernet4", "trunk-vlans": [100, 200]}
     ]
   }
 }

Validated with yangson, this instance passes. Three small edits each fail, and the messages below are the validator’s actual output.

Pointing Ethernet0 at VLAN 300, which no vlan entry defines, breaks the leafref:

                    
                        
SemanticError {/example-vlans:ports/port[name="Ethernet0"]/access-vlan} instance-required

Setting both access-vlan and trunk-vlans on Ethernet4 trips the must rule and returns the model’s own message:

                    
                        
SemanticError {/example-vlans:ports/port[name="Ethernet4"]/trunk-vlans[.="100"]} must-violation: Pick access-vlan or trunk-vlans for each port.

Defining VLAN 5000 falls outside the vlan-id type:

                    
                        
YangTypeError {/example-vlans:vlans/vlan[id="5000"]/id} invalid-type: not in range

Each error names the exact path to the bad field, which is what you want in a pull request review or a pipeline log.

The same gate scales up to the whole network operating system, where a SONiC lifecycle white paper lays out CI/CD pipelines and iterative regression runs around every release.

YANG Model Tutorial: Build and Validate Your First Module

This YANG model tutorial rebuilds the YANG data model example above on a laptop, so it doubles as a short YANG language tutorial. You need Python 3 and a text editor. Both YANG networking tools it uses are open source: pyang compiles the module, and yangson validates the data.

The common types come first. The IETF refreshed ietf-yang-types and ietf-inet-types in RFC 9911 in December 2025. That revision obsoletes RFC 6991 and adds types such as date, time, ip-address-and-prefix, host-name, email-address, and protocol-number. Use the 2025-12-22 revision of both modules so your types match what new standard models will import.

  1. Install the compiler and a validator with pip install pyang yangson.
  2. Extract ietf-yang-types from the RFC 9911 text with xym or rfcstrip and save it as ietf-yang-types@2025-12-22.yang in a working folder.
  3. Write your module in the same folder and name it module-name@revision.yang, so tools can match the revision.
  4. Run pyang –strict -p . example-vlans.yang and fix every error before going further.
  5. Print the tree with pyang -f tree -p . example-vlans.yang and check that each node’s rw or ro flag matches your intent.
  6. Write a yang-library.json file that lists your module and the IETF module with their revisions, so yangson knows exactly which schema to load.
  7. Load the library with yangson’s from_file, parse your JSON instance, and call validate() on it.
  8. Break the instance on purpose (a missing leafref target, a value out of range) and confirm each break fails with a clear path.
  9. Commit the model, the library file, and the test instances together, so the checks run again on every change.

Step 8 is the easiest to skip, and it is the only step that proves your constraints actually fire. A must expression with a typo can compile cleanly and never reject anything.

Wiring these checks into your infrastructure CI/CD pipeline is one step in an enterprise SONiC adoption plan, next to qualifying the release and the hardware, and model-level validation runs long before any testbed run.

Where YANG Models Come From: IETF, IEEE, OpenConfig, and Native

Four groups publish most of the YANG data models you will meet, and each one models the same interface or routing protocol from a different angle.

Source Who writes it Example modules What to expect
IETF Standards working groups ietf-interfaces (RFC 8343), ietf-routing Protocol-neutral, slow to change, widely referenced
IEEE and other bodies IEEE 802.1, MEF, BBF ieee802-dot1q-bridge Deep coverage of one technology
OpenConfig A working group of network operators openconfig-interfaces, openconfig-bgp Operator-driven, paired with gNMI, separate config and state branches
Native Each NOS or device maker sonic-vlan, vendor-specific modules Matches the device exactly, portable to no one else

An OpenConfig path such as /interfaces/interface[name=Ethernet0]/config/mtu has the same structure on every device that implements the model, with only the key values changing, which is the whole case for a vendor-neutral networking data model. Native models trade that portability for coverage: they expose every knob the device has, including ones no standard has named yet.

Every open network operating system has to map the standard models it supports onto its own internal state, and every new feature needs both sides of that mapping, which makes it a standing part of open NOS engineering.

Before you automate against any device, ask it what it supports instead of reading a datasheet. NETCONF servers advertise modules in their hello message and through the YANG library (RFC 8525, 2019), and gNMI targets answer a Capabilities request with the models and encodings they serve.

How SONiC Uses YANG Models for Its Configuration Database

SONiC stores its configuration as tables in a Redis database called CONFIG_DB. A VLAN is a key such as VLAN|Vlan100 with fields like vlanid and mtu, and the switch’s daemons read their settings from those tables. The layout is described in SONiC’s containerized NOS architecture, where each function runs in its own container and shares state through Redis.

Redis itself stores strings and enforces no schema. The SONiC project closes that gap with native YANG models, one per feature: on the master branch in October 2026, sonic-buildimage carried 143 sonic-*.yang files, from sonic-port and sonic-vlan to sonic-bgp-neighbor, sonic-macsec, and sonic-srv6.

Learn more about SONiC's architecture, its capabilities, and explore inspiring success stories of SONiC deployments across diverse network environments.

The models follow SONiC’s own guidelines: one module per feature, a top-level container named after the module, and one YANG container per CONFIG_DB table. Here is the VLAN ID from sonic-vlan.yang as the file reads today:

                    
                        
leaf vlanid {
   description "IEEE 802.1Q VLAN identifier (2-4094)";
   type uint16 {
     range 2..4094;
   }
   must "substring-after(../name, 'Vlan') = current()" {
     error-message "The vlanid must correspond to the VLAN name";
   }
 }

The must rule ties the key Vlan100 to the field vlanid: 100, so a table entry whose name and ID disagree fails validation. The range also starts at 2, stricter than the 802.1Q type in the example above. The same module uses leafrefs to bind each VLAN interface to an existing VRF and VNET.

What the Models Validate, and What They Skip

SONiC’s generic config updater, run as config apply-patch, applies an RFC 6902 JSON Patch to a copy of the running configuration, validates the result against the YANG models, and only then writes CONFIG_DB. Its patch sorter code, as changed in August 2026, refuses by default any patch that touches a table with no YANG model, and –dry-run shows the result without applying it.

Many everyday commands, such as config portchannel add and config interface ip add, run the same check only when yang_config_validation is set to enable in DEVICE_METADATA|localhost, and the model’s default is disable. Coverage is per command: on the master branch in October 2026, the config vlan group writes without it. Turn the flag on with config yang_config_validation enable, and treat apply-patch as the route that always validates.

Two limits are written into the code itself. A comment in the updater’s gu_common.py states that “YANG only validates state and not transitions,” so a rule about the order of changes lives in Python next to the model. A second list of validators for BGP peer groups and port lanes carries a note to move them into YANG later.

At the two extremes, apply-patch and a raw Redis write differ in one stop.

Two routes into SONiC's CONFIG_DB: a JSON patch sent with config apply-patch passes YANG validation before it is written, while a raw redis-cli write skips every model check and is stored as written.

The practical reading: a change made through apply-patch, or through a validating config command with the flag on, is checked against the model, while a value written straight into Redis with redis-cli skips every rule above.

Two Models for One Feature: OpenConfig on Top of SONiC YANG

YANG management on SONiC runs through its management framework, which adds a REST server that follows RESTCONF (RFC 8040), a gNMI server, and a CLI, all built on a translation library called Translib. Clients can speak standard models such as OpenConfig, and Translib converts each request into CONFIG_DB tables.

The management framework design, last revised in March 2025, spells out the cost. A feature exposed through a standard model needs a separate SONiC YANG model for validating the Redis data, plus transformer annotations that map the standard paths onto SONiC tables. One feature therefore carries two models and a mapping between them.

Followed end to end, one OpenConfig request passes through both models before it lands.

An OpenConfig request on SONiC travels from a gNMI or REST client through the Translib transformer, which maps the path to SONiC tables, then gets validated against SONiC's own YANG schema and lands in CONFIG_DB.

That mapping decides what works. An OpenConfig path answers on a SONiC switch only if the image you run includes a transformer for it, so the same gNMI request can succeed on one build and return an error on another.

If you maintain your own build, those mappings become code your team owns and re-tests on every rebase, one of the trade-offs weighed in owning a vendor-neutral SONiC distribution.

Model Revisions Change What Your Automation Can Write

YANG models change with the software, and SONiC’s revision statements are a poor record of when. Of the 12 commits that changed sonic-vlan.yang between May 2023 and June 2026, four added a revision statement, and their dates trail the merges: static anycast gateway support carries revision 2025-04-22 and merged in June 2026.

The other eight changed the file with no new revision, including an interface-name length limit in November 2024 and ordered-by user on the DHCP server lists in November 2025. A new optional leaf rarely breaks automation. A new length limit, a narrowed range, or a new must rule can, because a patch that validated on the old image now fails on the new one, which is a sound result that still stops a rollout.

Before you move a fabric to a new release, run these checks:

  • Diff the pyang -f tree output for every module your automation writes to.
  • Diff the module files in /usr/local/yang-models between the two images, since revision statements miss most changes.
  • Replay your stored test instances against the new models and confirm they still validate.
  • Run config apply-patch –dry-run with a typical change on a lab switch running the new image.
  • Re-check every OpenConfig path your tooling reads, since transformer coverage changes with the build.

Model drift is one of the reasons the choice of release carries weight, a point choosing the right SONiC version works through for different fabrics. Your test instances become a contract between your tooling and the switch, and the release you pick decides whether that contract holds.

Common YANG Modeling Mistakes in Network Automation

The YANG data modeling mistakes below share one root: treating the model as documentation instead of as an executable contract. The IETF’s updated guidelines for YANG authors, RFC 9907 from March 2026, address several of them directly.

Check your own models and tooling for each of these:

  • Putting a platform limit into max-elements on the list itself, where RFC 9907 says to use a deviation for the platform’s hard limit.
  • Copying the configuration tree into a separate -state tree, the pre-NMDA pattern RFC 9907 retires in favor of one tree under the datastore architecture from RFC 8342 (2018).
  • Stacking several deviation statements on one target in one module, which RFC 9907 advises against because evaluation order changes the result.
  • Validating examples by eye, where RFC 9907 names yangson and yanglint for checking JSON instances against their models.
  • Writing a module with no revision statement, which leaves tools unable to tell two versions apart.
  • Generating configuration from CLI templates while the device exposes the same data through a model.

Each item turns a review-time rule into a check a tool runs every time.

The upgrade side of the same contract is where a validated, frozen SONiC baseline pays off, because a fixed release means fixed models for as long as you stay on it.

Download the Product Brief

The PLVision LTS for SONiC® Product Brief covers the full feature matrix by deployment model, hardware compatibility list, lifecycle timeline, support tier breakdown, comparison against Community SONiC and alternative approaches, and extension paths for requirements beyond the standard LTS scope.

Start with One Model and One Validation Gate

The fastest way to get value from YANG is to pick the one table your automation changes most often, such as VLANs or BGP neighbors in a data center fabric, and put a validation gate in front of it. A model, three test instances, and a dry run in CI catch the class of error that a template never can.

The cost difference is easy to put in front of a manager: a change rejected in CI costs a review comment, while the same change found in production costs a maintenance window and a rollback on every switch it reached.

If you run SONiC in your own data center, start with the sonic-*.yang files your release ships in /usr/local/yang-models, since they describe exactly what your switches accept. Which of your current configuration changes would fail validation today if you ran them through apply-patch –dry-run?

Ready to explore how SONiC can enhance your business?

Book a call with our experts to discuss your use case and unlock the full potential of open, disaggregated networking.
Message:
Your message has been sent, thank you! We will contact you as soon as possible.
Vadym Hlushko

Frequently Asked Questions

What is the difference between YANG and NETCONF?

YANG is a data modeling language that defines the structure, types, and rules of configuration and state data. NETCONF is a protocol, defined in RFC 6241, that carries that data over SSH, and RESTCONF and gNMI carry the same YANG-modeled data.

What is a YANG leaf?

A leaf is a node that holds one typed value and has no children, such as an interface MTU or a VLAN name. A leaf-list holds several values of the same type, such as the trunk VLANs on a port.

What is a network data model?

It is a schema for network gear: a formal list of the settings a device accepts and the state it reports, with names, types, keys, and constraints that software can check a change against before applying it. The IETF and OpenConfig publish theirs in YANG.

What is the difference between OpenConfig and IETF YANG models?

IETF models come from standards working groups and aim to be protocol-neutral, while OpenConfig models come from a working group of network operators and are designed around gNMI and streaming telemetry. OpenConfig separates config and state branches under each node.

How do I validate a YANG data model?

Compile the module with pyang --strict to catch syntax and reference errors, then validate JSON or XML instances against it with yangson or yanglint, the two tools RFC 9907 names for checking examples. Keep instances that should fail, and confirm each fails with the expected path.